The following page source example displays a
TextBox
and its validation controls (RequiredFieldValidator & ValidationSummary
). The validation controls have the same ValidationGroup
defined, which allows us to validate different page elements independently. The page displays also a DIV
element that will cause the Validation action when clicked:<!-- Validation Summary -->
<asp:ValidationSummary ID="ValidationSummary1" runat="server"
HeaderText="Validation errors:" ValidationGroup="Group1"/>
<!-- TextBox and its validator -->
Name: <asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ErrorMessage="Name is required" Text="*"
ControlToValidate="TextBox1" ValidationGroup="Group1"> />
<!-- Div that causes client-side validation when clicked -->
<div onclick="Validate();" >Validate Form</div>
The code above should should produce smth like that when validation is triggered:
Now let's take a look at the custom JS code that triggers the validation. There are couple ways to do that:
- Easy way - works for all validators from the same ValidationGroup:
function Validate()
{
// If no group name provided the whole page gets validated
Page_ClientValidate('Group1');
} - If you want to validate only specific validators:
function Validate()
{
// Get the specific validator element
var validator = document.getElementById('RequiredFieldValidator1');
// Validate chosen validator
ValidatorValidate(validator);
// Update validation summary for chosen validation group
ValidatorUpdateIsValid();
ValidationSummaryOnSubmit(validationGroup);
}
Useful links:
5 comments:
This is very useful. I used this in combination with jquery to handle blur and click events for validating checkboxes (terms and conditions) and radio choices being selected. Good stuff man, my validations are all synced with asp.net. I appreciate it.
Very helpfull thank you!
Wow! You've just helped me solve a pretty stupid requirement. Thanks!
Loved it! thank you.
I had been using Page_ClientValidation but recently this has been failing for Mac users. It cannot recognize the Page_ClientValidation and just passed through it.
Post a Comment