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: