How to call JavaScript function when ASP.Net validators succeed? - javascript

I have a webform with ASP.Net controls and Validators for them setup into a group. I am trying to execute some JavaScript that occurs only when the validators succeed, to prevent the user from going onto the next step of the form without completing the requirements.
However, I cannot seem to get this to work properly. The JavaScript either executes without validation completing, or the JavaScript won't execute when validated successfully. I have a sneaking suspicion that this is due to the combination of HTML Required="true" tags, and ASP.Net validators behaving differently.
ASP.Net
<asp:TextBox ID="EmailAddress" runat="server" TextMode="Email" Required="true" ValidationGroup="Group1" />
<asp:TextBox ID="Password1" runat="server" TextMode="Password" Required="true" ValidationGroup="Group1" />
<asp:RegularExpressionValidator ID="valPassword" runat="server" ControlToValidate="Password1"
ErrorMessage="Your password doesn't meet the strength requirements"
ValidationExpression="^(?=.*\d)(?=.*[a-z])(?=.*[/W_].*)(?=.*[A-Z]).{8,255}"
ValidationGroup="Group1" ></asp:RegularExpressionValidator>
<asp:TextBox ID="Password2" runat="server" TextMode="Password" Required="true" ValidationGroup="Group1"
/>
<asp:CompareValidator runat="server" ControlToCompare="Password1" ControlToValidate="Password2"
ErrorMessage="Your entered passwords do not match." ValidationGroup="Group1" />
<asp:Button ID="btnNext" runat="server" Text=">" OnClientClick="pgNext();" ValidationGroup="Group1" />
JavaScript
function pgNext() {
if (Page_ClientValidate("Group1")) {
$('.register-page1').css('display', 'none');
$('.register-page2').css('display', 'block');
} else {
}
}

Call your page validator, then check if page is valid, then finally call your js function.
In your button click event:
Page.Validate("validationGroupNameHere");
if(Page.IsValid)
{
// click code here
//then call your js function
Page.RegisterStartupScript(Page, Page.GetType(), "callMe", " jsFunctionNameHere();", true);
}

Related

ASP.NET client side validation on blur

I have few textboxes and asp.net validation controls on a page. The validation fires when I click on "Submit" button. Is there anyway to fire the validation as soon as I leave the textbox? I would like to do the same validation for other 20+ fields in the form. However, only validating specific textbox when leaving it.
<asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
<asp:RangeValidator ID="rvclass"
runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
<asp:Button ID="btnsubmit" runat="server" onclick="btnSubmit_Click" Text="Submit" />
Create a js function to perform the validating, then for each textbox you want to validate set the onblur and call that function. (I'm just free writing below so excuse the syntax error but you should get the gist)
function validateClass(val)
{
if(val.value > 5 && val.value < 13)
{
//alert(good!)
}
else
{
//alert(show error?)
}
}
call it in your textbox
<asp:TextBox ID="txtclass" runat="server" onblur="validateClass(this);"></asp:TextBox>

Button in asp.net doesn't work sometimes

I have a textbox and a button in my code.The button when clicked should validate the value entered in the textbox.The button most of the times does it but at times doesn't do anything at all.Any help would be appreciated.
<asp:Button ValidationGroup="vgpPno" runat="server" ID="btnSubmitPartNumber" OnClick="btnSubmitPartNumber_Click" SkinID="MSWButton" Text="OK" OnClientClick="if(Page_ClientValidate(){startPLI();}meta:resourcekey="btnSubmitPartNumberResource1" />
<asp:TextBox runat="server" ValidationGroup="vgpPno" SkinID="MSWTextBox"
ID="tbPARTNUMBER" MaxLength="11" meta:resourcekey="tbPARTNUMBERResource1" Width="230" Style="display: inline" CssClass="form-control input-sm"></asp:TextBox>
<asp:Button ValidationGroup="vgpPno" runat="server" ID="btnSubmitPartNumber" OnClick="btnSubmitPartNumber_Click" SkinID="MSWButton" Text="OK"
OnClientClick="if(Page_ClientValidate(){startPLI();}meta:resourcekey='btnSubmitPartNumberResource1'" />
Check Your web Form. If you are using form tag more then one time asp.controls not working properly

Validation (Page_ClientValidate('mygroup')) returns always true after postback

i have a page which i do some validations , all my validations are client side expected one which it use server validation. So my problem is when i fire the server side validation and the page postbacks, this function Page_ClientValidate('mygroup') return true, so i lose my validation though my required fields aren't.
function DoValidation() { var validated = Page_ClientValidate('NewMemberRequired'); Page_BlockSubmit = false; return validated; }
<telerik:RadButton ID="btnSave" runat="server" Text="Save & Close" OnClick="btnSave_Click" CausesValidation="true"
OnClientClick="return DoValidation();">
//the fields
<asp:RequiredFieldValidator ID="AddressRequired" runat="server" ControlToValidate="Address"
CssClass="ErrorMessage" ErrorMessage="Required"ValidationGroup="mygroup"><asp:RequiredFieldValidator/>
//an other filed with postback=true
<telerik:RadTextBox ID="age" runat="server" AutoPostBack="True" OnTextChanged="age_TextChanged">
read the documentation on using RadButton's client-side events as your approach will not work even if it does not cause errors: http://www.telerik.com/help/aspnet-ajax/button-onclientclicking.html. This can also help: http://blogs.telerik.com/aspnet-ajax/posts/12-08-10/migrating-onclientclick-handlers-from-asp-button-to-telerik-s-asp-net-ajax-button.aspx
Read the documentation on executing custom validation: http://www.telerik.com/help/aspnet-ajax/button-validation-with-postback-confirm.html
Make sure your validation grops are fine because in the provided snippet they do not match
the AutoPostBack=true for a textbox will have it postback when you delete its text, regardless of the validator in this setup
Here is some code that validates well:
<telerik:RadButton ID="btnSave" runat="server" Text="Save & Close" OnClick="btnSave_Click" CausesValidation="true"
OnClientClicking="DoValidation">
</telerik:RadButton>
//the fields
<asp:RequiredFieldValidator ID="AddressRequired" runat="server" ControlToValidate="Address"
CssClass="ErrorMessage" ErrorMessage="Required" ValidationGroup="mygroup">
</asp:RequiredFieldValidator>
//an other filed with postback=true
<telerik:RadTextBox ID="Address" runat="server" AutoPostBack="True" OnTextChanged="age_TextChanged" ValidationGroup="mygroup" CausesValidation="true">
</telerik:RadTextBox>
<script>
function DoValidation(sender, args) {
var validated = Page_ClientValidate('mygroup');
args.set_cancel(!validated);
Page_BlockSubmit = false;
}
</script>
Changes:
proper use of OnClientClicking event
proper ValidationGroups being set
CausesValidation=true for the etxtbox so deleting its text will cause validation and prevent the postback

Field is validated when loosing focus

I'm doing validation of a textbox with RequiredFieldValidation.
I want it to validate the textbox only when a button is clicked, not when textbox loses focus.
Now, every time when I click anywhere else on a page it shows an error message.
Here is a code:
<asp:TemplateField HeaderText="Email">
<ItemTemplate>
<asp:TextBox runat="server" ID="txtEmail" Text='<%#Eval("CustEmail") %>' />
<asp:RequiredFieldValidator ControlToValidate="txtEmail"
ValidationGroup="grpEmail"
ErrorMessage="Must enter Email Address" runat="server"></asp:RequiredFieldValidator>
<asp:Button Text="Update Email" ButtonType="Button" CommandName="UpdateEmail"
ValidationGroup="grpEmail"
CausesValidation="true"
Visible="true" runat="server"/>
</ItemTemplate>
</asp:TemplateField>
I just need it to be validated when button is clicked. That's it.
What am I doing wrong?
Setting the attribute CausesValidation of the Textbox to false should do the trick.

Triggering Validators validating a control using js

I have a setup similar to this:
<asp:TextBox ID="txtEmail" runat="server"/>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtEmail" ErrorMessage="Required field cannot be left blank."
Display="Dynamic"/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="Invalid email address." ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
Display="Dynamic"/>
Now, I'm running some sort of js code which will change the value of the textbox, and I'd like to force the validators to trigger again. The JS code I'm using is intended to be modular, so when it triggers I don't know the name of the validation group, whether the control has a validator attached to it or whatever.
I've ended up using
Page_ClientValidate()
But the page itself is going to have more than one validator, and I don't want them all the pop up at the same time.
So the basic question is - is there a way that I can get a list of validators 'related' to a control, and force them to revalidate the input?
(To clarify - the code I posted above is just to explain my problem better. It's not the actual code I'm using)
You can associate the email validators with a validation group (for example "emailValidationGroup") :
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtEmail" ErrorMessage="Required field cannot be left blank."
Display="Dynamic" ValidationGroup="emailValidationGroup"/>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ErrorMessage="Invalid email address." ControlToValidate="txtEmail"
ValidationExpression="\w+([-+.']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*"
Display="Dynamic" ValidationGroup="emailValidationGroup"/>
and then call : Page_ClientValidate("emailValidationGroup");

Categories