ASP.NET client side validation on blur - javascript

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>

Related

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

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);
}

can a required field validator can have two validation groups?

I am working on a web page.
In that web page there are 4 text boxes and each one has required field validator.
The web page has 3 buttons.
on clicking on 1st button 1st & 2nd required field validations should fire.
and on 2nd button 2nd and 3rd required field validator should fire
just like this on 3rd button 3rd and 4th should fire.
The problem is , since the one required field validator is invoked with two buttons i cant have a validation group name .
can anybody please suggest a solution .
it will be really helpful.
You can use JS, where you validate specific groups. For each button create separate validation method.
<script type="text/javascript">
function validateGroup12() {
var g1 = Page_ClientValidate("vgroup1");
var g2 = Page_ClientValidate("vgroup2");
if (!g1 || !g2) return false;
return true;
}
</script>
.aspx edit RequiredFieldValidator and set groups name into ValidationGroup
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ValidationGroup="vgroup1,vgroup2" Display="Dynamic">
Have two validators, instead of one validator, for Textbox 2 and Textbox 3 with the validation groups properly set to the corresponding button validation group.
Even though this is going to duplicate the validator, this simplifies your logic.
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ValidationGroup="vgroup1" Display="Dynamic">
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBox2" ValidationGroup="vgroup1" Display="Dynamic">
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
ControlToValidate="TextBox2" ValidationGroup="vgroup2" Display="Dynamic">
<asp:Button ID="Button1" runat="server" Text="Button" ValidationGroup="vgroup1" />
<asp:Button ID="Button2" runat="server" Text="Button" ValidationGroup="vgroup2" />

Inserting a textbox value in Javascript doesn't pass ASP.NET validation

I have an ASP.NET 4.5 web form with inputs for a physical and mailing address. After entering a physical address, a user can tick a checkbox to fill in the mailing address if the information is the same.
This occurs via an OnClick function tied to the checkbox, which basically does this (I left out additional code):
document.getElementById("<%= txtMailAddressStreetNumber.ClientID%>").value = document.getElementById("<%= txtPermAddressStreetNumber.ClientID%>").value;
Each of the address textboxes has a RequiredFieldValidator. When I submit the form, it passes client-side validation and posts back to the server. There it fails (Page.IsValid is false). The textboxes that were populated by the OnClick function fail server-side validation unless I manually populate them.
I've tried calling Page_ClientValidate('FormGroup'); (FormGroup is the name of the validation group) after assigning values, and doing this doesn't trigger any validation error messages for the textboxes. However, when I submit the form (postback), the values inserted via Javascript are all cleared and I have to manually enter them.
Code in the .aspx page:
<asp:Label CssClass="mainlabel" ID="lblPermAddressZipCode" runat="server" Text="Zip Code" AssociatedControlID="txtPermAddressZipCode" />
<asp:RequiredFieldValidator ControlToValidate="txtPermAddressZipCode" ID="RequiredFieldValidator10" runat="server" ErrorMessage="*" Display="Dynamic" ValidationGroup="FormGroup" CssClass="formerror" />
<asp:TextBox ID="txtPermAddressZipCode" Width="100" onclick="openDialog(1)" ReadOnly="true" CssClass="readOnlyTextBox" runat="server" />
<asp:CheckBox ID="cbPermIsMailAddress" onclick="UsePermanentAsMailingAddress()" runat="server" /><small>(same as above)</small>
<asp:Label CssClass="mainlabel" ID="lblMailAddressZipCode" runat="server" Text="Zip code" AssociatedControlID="txtMailAddressZipCode" />
<asp:RequiredFieldValidator ControlToValidate="txtMailAddressZipCode" ID="RequiredFieldValidator15" runat="server" ErrorMessage="*" Display="Dynamic" ValidationGroup="FormGroup" CssClass="formerror" />
<asp:TextBox ID="txtMailAddressZipCode" ReadOnly="true" onclick="openDialog(2)" CssClass="readOnlyTextBox" Width="100" runat="server" />
Javascript:
function UsePermanentAsMailingAddress() {
//only copy if the address is complete
if (document.getElementById("<%= permCityStateZipId.ClientID %>").value != '') {
//exit if the box was unchecked
if (!$("#<%= cbPermIsMailAddress.ClientID%>").is(':checked')) {
return;
}
document.getElementById("<%= txtMailAddressZipCode.ClientID%>").value = document.getElementById("<%= txtPermAddressZipCode.ClientID%>").value;
//the ID value is the answer
document.getElementById("<%= mailCityStateZipId.ClientID%>").value = document.getElementById("<%= permCityStateZipId.ClientID %>").value;
//Page_ClientValidate('FormGroup');
}
else {
$("#<%= cbPermIsMailAddress.ClientID%>").removeAttr('checked');
alert("Please enter a complete permanent address first.");
}
}
Since the ReadOnly property is set in the .aspx, any changes made to it client-side will be ignored when it's posted back. If you absolutely need to have the textboxes read-only, then remove the property from your .aspx and set it with JavaScript on page load:
$(document).ready(function () {
$('#<%= txtMailAddressZipCode.ClientID%>').prop('readonly', true);
});
This way the user won't be able to directly change the textbox (I assume you have some other way of filling the textbox), but any changes will be posted back rather than the original (empty) values.

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

How disable RequiredFieldValidator in script

I have TextBox with RequiredFieldValidator on my page.
I also have link that calls some simple javascript.
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator
ID="RequiredFieldValidator4" runat="server" ControlToValidate="TextBox1"
Display="Dynamic" />
<asp:LinkButton ID="Link1" runat="server" OnClientClick="DoSomething(); return false;" CausesValidation="false"Text="Do" />
function DoSomething() {
textbox1.val("blah"); }
When user type something into textbox and then delete that text and focus next control - then validator fires.
Then user can use link that adds text using javascript. TextBox1 text is no longer empty but RequiredFieldValidator still shows error message. How to prevent that?
you can use javascript ValidatorEnable function
ValidatorEnable(document.getElementById('<%= ValidatorID.ClientID %>'), true);
I would recommend a CustomValidator here since you do NOT want the normal RequiredFieldValidator behavior. The CustomValidator client method will only run on postback.
The whole point of the validators is that they are to be used for both server side and client side validation.
If you only want to validate on the server side, don't use a validator and simply check that the values are valid and report an error.

Categories