Validation Controls
ASP.NET Web Forms provides a rich set of validation controls that enable you to validate user input on both the client-side (using JavaScript) and the server-side. This ensures data integrity and improves the user experience by providing immediate feedback.
Common Validation Controls
RequiredFieldValidator
Ensures that a specified input control is not empty. This is useful for mandatory fields like usernames, passwords, or email addresses.
Properties:
ControlToValidate: The ID of the input control to validate.ErrorMessage: The message displayed if validation fails.Display: How the error message is displayed (Static,Dynamic,None).EnableClientScript: Whether to enable client-side validation (default istrue).
Example:
<asp:TextBox ID="txtUsername" runat="server" />
<asp:RequiredFieldValidator ID="rfvUsername" runat="server"
ControlToValidate="txtUsername"
ErrorMessage="Username is required."
Display="Dynamic">
</asp:RequiredFieldValidator>
RegularExpressionValidator
Validates the input of a control against a predefined or custom regular expression. This is powerful for validating formats like email addresses, phone numbers, or postal codes.
Properties:
ControlToValidate: The ID of the input control to validate.ErrorMessage: The message displayed if validation fails.ValidationExpression: The regular expression to use for validation.
Example (Email Validation):
<asp:TextBox ID="txtEmail" runat="server" />
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ErrorMessage="Please enter a valid email address."
ValidationExpression="^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$"
Display="Dynamic">
</asp:RegularExpressionValidator>
CompareValidator
Compares the value of a control against another control's value or a fixed value. Useful for password confirmation or date range validation.
Properties:
ControlToValidate: The ID of the input control to validate.ControlToCompare: The ID of the other input control to compare against (if applicable).ValueToCompare: A fixed value to compare against (if applicable).Operator: The comparison operator (Equal,NotEqual,GreaterThan,GreaterThanEqual,LessThan,LessThanEqual,DataTypeCheck).Type: The data type for comparison (String,Integer,Date,Double,Currency).
Example (Password Confirmation):
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" />
<asp:TextBox ID="txtConfirmPassword" runat="server" TextMode="Password" />
<asp:CompareValidator ID="cvConfirmPassword" runat="server"
ControlToValidate="txtConfirmPassword"
ControlToCompare="txtPassword"
ErrorMessage="Passwords do not match."
Operator="Equal"
Type="String">
</asp:CompareValidator>
RangeValidator
Validates that the value of a control falls within a specified range (minimum and maximum values).
Properties:
ControlToValidate: The ID of the input control to validate.MinimumValue: The minimum allowed value.MaximumValue: The maximum allowed value.Type: The data type for comparison (String,Integer,Date,Double,Currency).
Example (Age between 18 and 99):
<asp:TextBox ID="txtAge" runat="server" />
<asp:RangeValidator ID="rvAge" runat="server"
ControlToValidate="txtAge"
MinimumValue="18"
MaximumValue="99"
Type="Integer"
ErrorMessage="Age must be between 18 and 99.">
</asp:RangeValidator>
CustomValidator
Allows you to perform custom validation logic using either client-side JavaScript or server-side C#/VB.NET code.
Properties:
ControlToValidate: The ID of the input control to validate.ClientValidationFunction: The name of the JavaScript function to execute for client-side validation.OnServerValidate: The name of the server-side event handler.
Example (Client-side):
// JavaScript function in your .aspx page or .js file
function ValidateCustomInput(sender, args) {
if (args.Value.length > 5) {
args.IsValid = true;
} else {
args.IsValid = false;
}
}
<asp:TextBox ID="txtCustom" runat="server" />
<asp:CustomValidator ID="cvCustom" runat="server"
ControlToValidate="txtCustom"
ClientValidationFunction="ValidateCustomInput"
ErrorMessage="Input must be longer than 5 characters."
ValidateEmptyText="true">
</asp:CustomValidator>
Validation Groups
Validation groups allow you to associate specific validation controls with a particular button click. This is useful when you have multiple forms on a single page or want to perform different sets of validations.
Set the ValidationGroup property on both your validation controls and the buttons that trigger validation.
<asp:TextBox ID="TextBox1" runat="server" />
<asp:RequiredFieldValidator ID="rfv1" runat="server"
ControlToValidate="TextBox1"
ErrorMessage="Field 1 is required."
ValidationGroup="Group1">
</asp:RequiredFieldValidator>
<asp:Button ID="btnSubmitGroup1" runat="server" Text="Submit Group 1" ValidationGroup="Group1" />
ValidationSummary Control
The ValidationSummary control displays a summary of all validation errors on the page. It can display errors as a bulleted list or in a table.
<asp:ValidationSummary ID="vsSummary" runat="server"
ShowModelStateErrors="true"
HeaderText="Please correct the following errors:" />
Please correct the following errors:
- Username is required.
- Please enter a valid email address.
Client-Side vs. Server-Side Validation
By default, ASP.NET Web Forms validation controls perform both client-side and server-side validation. This provides a responsive user experience and a robust safety net.
- Client-Side: Performed in the user's browser using JavaScript. Provides immediate feedback without a round trip to the server.
- Server-Side: Performed on the web server. Essential for security and data integrity, as client-side validation can be bypassed.
You can disable client-side validation by setting EnableClientScript="false" on individual validation controls or globally in the page's directive.