I have 2 textbox, one for login another for password.
I have 1 custom server side validator too, if password is entered wrong, validator is fired.
What I want is to set focus on this error message.
I have tried focus(), and setfocusonerror property too. but its not working.
here is my code:
<asp:CustomValidator ID="cvLogin"
runat="server"
Display="Dynamic"
CssClass="login-req"
OnServerValidate="cvLogin_ServerValidate"
ValidationGroup="tovalidate"
SetFocusOnError="True">
</asp:CustomValidator>
protected void cvLogin_ServerValidate(object source,
ServerValidateEventArgs args)
{
if (currentUser == null)
{
args.IsValid = false;
MessageBox1.Focus();
MessageBox1.SetMessage(Resources.RSResource.Login_InvalidLogin,
Constants.MessageType.Error);
}
Try SetFocus method of Page:
if (currentUser == null)
{
args.IsValid = false;
Page.SetFocus(MessageBox1);
...
}
I am not sure. But may be you need to place your control on a Panel.
UPDATE 2:
I checked SetFocus method. It works for TextBoxes, but doesn't work for Labels or Validators. So if you want to set focus on message the best choise is using javascript:
document.getElementById('MessageBox1').scrollIntoView(true);
I also tested this server side code. It works fine:
Page.ClientScript.RegisterStartupScript(this.GetType(), "FocusScript", "document.getElementById('MessageBox1').scrollIntoView(true);", true);
Related
In My Application server side validation function is not working.even function is not called. i have put debugger on thuat function but it is not stopped ny debugger .i.e. function is not called
<asp:TextBox type="text" ID="txtMobilePhone" runat="server" ClientIDMode="Static" CausesValidation="true"/>
<asp:CustomValidator ID="cvMobilePhone" runat="server" OnServerValidate="cvMobilePhone_ServerValidate"
Text="Mobile Phone already exist in this Reward Program." ErrorMessage="Mobile Phone already exist in this Reward Program."
Display="Dynamic" ValidationGroup="vgStep2" ControlToValidate="txtMobilePhone" CssClass="error"></asp:CustomValidator>
<asp:RequiredFieldValidator ID="rfvMobilePhone" runat="server" ControlToValidate="txtMobilePhone"
ErrorMessage="Mobile Phone is required." CssClass="error" ValidationGroup="vgStep2"></asp:RequiredFieldValidator>
<asp:CustomValidator ID="cvMobilePerVal" runat="server" ClientValidationFunction="validateEmailOrMobilePerVal"
Display="Dynamic" ValidationGroup="vgStep2"></asp:CustomValidator>
<asp:Button ID="btnStep2Upper" runat="server" ClientIDMode="Static" OnClick="btnSaveContactClick" Text="Save" ValidationGroup="vgStep2" vg="vgStep2" OnClientClick="return ClientValidate();" />
Server Side Code
protected void cvMobilePhone_ServerValidate(object source, ServerValidateEventArgs value)
{ /* I have put debugger here but control is not coming here*/
/* my validation logic*/
protected void cvMobilePhone_ServerValidate(object source, ServerValidateEventArgs value)
{
if (txtMobilePhone.Text.Trim() != "")
{
RewardProgramDataContext db = new RewardProgramDataContext();
Boolean f = false;
string MobilePhone = cmnFunc.RemoveMobilePhoneFormat(txtMobilePhone.Text.Trim());
if (Request["id"] != null)
{
var cData = db.spContactSelectAllSingle(new Guid(Request["id"])).SingleOrDefault();
if (cData != null)
{
if (cmnFunc.RemoveMobilePhoneFormat(cData.MobilePhone) == MobilePhone)
{
f = true;
value.IsValid = true;
}
}
}
if (f == false)
{
var res = db.spContactDuplicateMobile(new Guid(ddlContactList.SelectedValue), MobilePhone).SingleOrDefault();
if (res.Column1 <= 0)
{
value.IsValid = true;
customIsValid = true;
}
else
{
value.IsValid = false;
customIsValid = false;
}
}
}
}
now when i click submit button all clent side validation working but serside custom validator is not calling
You forget to set the ControlToValidate property?
<asp:CustomValidator ID="cvMobilePhone" runat="server" ControlToValidate="txtMobilePhone" OnServerValidate="cvMobilePhone_ServerValidate"
Text="Mobile Phone already exist in this Reward Program." ErrorMessage="Mobile Phone already exist in this Reward Program."
Display="Dynamic" ValidationGroup="vgStep2" CssClass="error"></asp:CustomValidator>
You have a combination of two different things causing this behaviour.
Firstly, note that although—as has been said by others—you do not have to specify ControlToValidate, doing so restricts the circumstances in which the server-side custom validation event will fire. Specifically, if you leave it unset, the event always fires on postback, whereas if you set it, the event only fires when the control identified by ControlToValidate has a non-empty value.
Secondly, by specifying OnClientClick, you are telling the framework that you will take care of client-side validation, which will now not fire unless you call it from your OnClientClick function. Although you have not included your ClientValidate function in your question, I suspect you are not doing so, which leaves your RequiredFieldValidator powerless to prevent the postback.
In combination, these two things mean that
the postback occurs despite the empty textbox, and
the server-side custom validation does not fire on postback, because of the empty textbox.
You can call the client validation from your custom function using Page_ClientValidate()), which will be present in your page script since the page contains validators.
function ClientValidate() {
if (Page_ClientValidate()) {
//do custom validation, maybe return false
return true;
}
else {
return false;
}
}
I'm adding validation to an existing asp.net web app built with web form. The input textbox controls I need to validate are created dynamically on the server side.
While creating the textboxes, I can also create RangeValidator controls and set its ControlToValidate to the ID of the textbox.
When validation fails, RangeValidator displays an error message at where the validation control is placed.
But I rather change the border or background-color to red of the textbox instead. How can that be done?
You can add custom logic to your validators both sever side and client side. check this link for help. http://msdn.microsoft.com/en-us/library/f5db6z8k%28v=vs.90%29.aspx
I'm not sure if you want help validating or changing the color (or both), but I just tried this little two-button app and it seems to work. Granted, I'm not using any dynamic control names and banking that "testText" is the first and only "testText" control on the page. You might also want to add some validation to ensure the control exists.
private void button1_Click(object sender, EventArgs e)
{
TextBox tb = new TextBox();
tb.Name = "testText";
this.Controls.Add(tb);
}
private void button2_Click(object sender, EventArgs e)
{
TextBox tb = (TextBox)this.Controls.Find("testText",true)[0];
tb.BackColor = System.Drawing.Color.Red;
}
As Irfan said, you can use a custom validator and implement on the server validate event the logic. However, a more direct aproach would be to check if the page is valid and the check if the rangevalidator is not valid. Keep in mind to set the displaymode to none if you don't want the validator to render any message.
if(!Page.IsValid && !myRangeValidator.IsValid)
{
// simplified, you will need to search for the control in the whole hierarchy
var ctrlToValidate = Page.FindControl(myRangeValidator.ControlToValidate) as WebControl;
if(ctrlToValidate != null)
{
ctrlToValidate.BorderColor = Color.Red;
}
}
this being said, I prefer the custom validator approach. The good thing is you can almost reuse all the code above. Just remove the first if, add the range validation, set the args.IsValid = false and then use the rest of the code.
Loop over all validators and add specific CSS class to controls. I use master page, so need to find controls in content placeholder.
const string ErrorCssClass = "error";
Validate();
if (IsPostBack && !IsValid)
{
var content = Form.FindControl("MainContent") as ContentPlaceHolder;
foreach (BaseValidator validator in Validators)
{
if (validator.IsValid)
continue;
var controlToValidate = content.FindControl(validator.ControlToValidate) as WebControl;
if (controlToValidate != null && !controlToValidate.CssClass.Contains(ErrorCssClass))
controlToValidate.CssClass += " " + ErrorCssClass;
}
}
I added a regex validator but its not showing anything on the page, basically the validation is done somewhere else i just needed to fire up. Here is the validator
<div>
<asp:RequiredFieldValidator
ID="RegularNoCardAccepted" runat="server"
ControlToValidate="txtCreditCardNumber"
CssClass="Error" Display="Dynamic">
</asp:RequiredFieldValidator>
</div>
And here is how I am trying to fire up, in reality i dont need it to check against a regular expression, I am just not sure how to make it pop up when it meets this condition
if (CardNotAccepted())
{
//Find the validator located somewhere in the master page.
RequiredFieldValidator reqVal =
FindControlRecursive(this.Page.Master, "RegularNoCardAccepted")
as RequiredFieldValidator;
if (reqVal != null)
{
//The code goes through here but it never shows.
reqVal.Enabled = true;
reqVal.Text = "Credit Card Type is not accepted";
reqVal.Visible = true;
reqVal.Validate();
}
return;
}
ASP.NET FieldValidators work automatically (assuming the Enabled property is set to true) on POST events. Here is an example of use: http://www.w3schools.com/aspnet/showasp.asp?filename=demo_reqfieldvalidator
So I've got this button:
<asp:Button runat="server" ID="btnSubmit" meta:resourcekey="btnSubmit" CausesValidation="true" OnClick="btnSubmit_Click" />
meta:resourcekey is for Localization Resources, doesn't concern us here - as we can see it has got an OnClick-Method and causes Validation.
That works fine, too, but I'd like to disable that button after the user clicked it so he/she can't click it multiple times before the PostBack succeeds, so here's what I did in Page_Load:
btnSubmit.Attributes.Add("onclick", "this.disabled=true;" +
Page.ClientScript.GetPostBackEventReference(btnSubmit, "").ToString());
onclick I'm disabling the button and re-adding the PostBackReference necessary for the OnClick-Method.
Problem: CausesValidation is gone, sadface. How exactly would I re-add that in CodeBehind or alternatively - What's an entirely different solution to this?
My Button has to:
a) disable itself after clicking, yet be enabled after the postback
b) have an OnClick CodeBehind Method
c) cause Validation
Thanks,
Dennis
Just override the Onload event of ur page or master page with
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
// prevents form from being submitted multiple times in MOST cases
// programatic client-side calls to __doPostBack() can bypass this
Page.ClientScript.RegisterOnSubmitStatement(GetType(), "ServerForm",
"if (this.submitted) return false; this.submitted = true; return true;");
}
Try the following in Page_Load
VB
Dim postBackOptions As PostBackOptions = New PostBackOptions(btnSubmit)
btnSubmit.OnClientClick = "this.disabled=true;"
btnSubmit.OnClientClick += ClientScript.GetPostBackEventReference(postBackOptionClaim)
C#
PostBackOptions postBackOptions = new PostBackOptions(btnSubmit);
btnSubmit.OnClientClick = "this.disabled=true;";
btnSubmit.OnClientClick += ClientScript.GetPostBackEventReference(postBackOptionClaim);
EDIT
if(Page_ClientValidate()) {this.visibility='hidden';}
If you need to have server side validation before you know whether to hide/disable the button or not you'll probably want to forgo the disabling of the button and just make sure your server-side code doesn't execute more than necessary if a user hammers on the button.
You could put a hidden field and generate a GUID for it in the page_load if(!IsPostBack) then on your btnSubmit_click do something like
if(Session[Page.ToString() + "_spam"] != null && Session[Page.ToString() + "_spam"] == hdnGuid.Value) {
return
} else {
Session[Page.ToString() + "_spam"] = hdnGuid.Value;
//do stuff
}
So I'm putting together a little registration area for my web project, here. The user inputs various strings such as "Username", "Password", etc.
I already have a bit of code set up in order to prevent duplicate Usernames or Passwords in the database. I also have a guard in place if the "Password" and "Repeat Password" fields don't match.
What I'm trying to do now is to -
1: If the user attempts to Submit data while a field is blank, it will not post.
2: Display a "Fields cannot be blank" div I've assigned "display: none" to.
I was thinking something along the lines of assigning the input fields a class of "Required", and using some sort of code such as
if == null
.show;
return false; //To prevent the rest of the function (the submit button posting to login/register) from firing.
Running into obscene problems. Anyway. Here's what I have so far.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
});
Any thoughts? At first I thought that I literally -cannot- use "class" to mark an input field, and then have that input field compared to a null value. I don't know, though.
You should use the .submit() jquery event handler on the form instead of .click() on the button. Then return false to prevent the normal form submission if needed.
Since you are trying to submit the form using $.post you should stop the default behavior of the form submit by alwasy returning false from submit button click handler.
$("#SubmitButton").click(function () { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return false; //And nothing else fires
}
$.post("login/register", $('#ConfirmPanel *').serialize(), function (result) {
if (result == 2) //Json return from C#
$("#UsernameInUse").show(); //Shows an error div
else if (result == 3) //Json return from C#
$("#EmailInUse").show(); //Shows an error div
else {
$("#ConfirmPanel").dialog('close'); //Closes the registration dialog
}
});
return false;
});
The jQuery way of preventing form submission is to use preventDefault(), like:
$("#SubmitButton").click(function (event) { //Click Submit
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
event.preventDefault(); //And nothing else fires
return;
}
//...
});
However, since you are posting the form asynchronously when validation passes, what you really want is something more along the lines of:
$("#SubmitButton").click(function (event) { //Click Submit
event.preventDefault(); //we don't ever want to allow the default behavior
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
});
The rest of what you suggest (using a class to mark each required input field, checking them all for empty strings) is reasonable.
Be aware that because you are binding the button's click event instead of the form's submit event it is entirely possible for the user to submit your form without ever clicking on your button and triggering your validation code. For instance, by pressing return from any one of your text fields.
Also note that in this case you may find it more convenient to just use a traditional onsubmit directive on the form, like:
<form onsubmit="validateAndPost(); return false;">
<!-- inputs and buttons, etc. -->
</form>
<script>
function validateAndPost() {
if ($("#PassReg").val() != ($("#PassConfirm").val())) { //Both fields match
$("#PasswordMismatch").show(); //Or this div shows you messed up
return;
}
//post the form
}
</script>
Example: http://jsfiddle.net/AwxGE/
I admire your desire to use jquery, however I would advise using a normal ASP.NET ReqiredFieldValidator control. As well as making your page substantially more concise and easy to maintain, it also allows you to very simply invoke server-side validation:
public void submitbutton_click(object sender, EventArgs args){
Page.Validate();
if(Page.IsValid){
doStuff();
}
}
Please don't reinvent the wheel, and don't trust the browser to behave as you think it will.
use this -
$(document).on('click', '#SubmitButton', function () {
`enter code here`
});