Validation Controls in ASP.NET

Validation controls are very useful while submitting data into a database table. These controls prevent users from submitting the wrong type of data. There are six validation controls available in the ASP.NET.

  • RequiredFieldValidator
  • RangeValidator
  • CompareValidator
  • RegularExpressionValidator
  • CustomValidator
  • ValidationSummary
By default, the validation controls perform validation on both the client (the browser) and the server. These validation controls uses JavaScript to perform validation on client-side. Client side validation is very fast because user gets immediate response whenever user enters an invalid value into a form field. Sometimes browsers (mobile browsers) do not support javascript. If a browser does not support JavaScript, then server side validation still perform. Validation controls supports EnableClientScript property.You can disable client-side validation by assigning the value False to EnableClientScript property of validation controls.

The validation controls inherit from the BaseValidator class therefore they inherit its properties and methods. BaseValidator class is an abstract class.

Using Page.IsValid:

Validation controls supports an IsValid property that returns the value True if there is no validation error. Also the Page.IsValid property returns the value True when the IsValid property of the validation controls in a page returns the value True.

Display Property

All the validation controls supports a Display property that ensures how the validation error message will be displayed.

Following are the three possible values:

  • Static
  • Dynamic
  • None
By default, the Display property has the value Static.

RequiredFieldValidator

RequiredFieldValidator control is used to make an input control as a mandatory field or the input field should not be empty. The other validation controls do not validate for an empty field. They validate, when user enter the data.

For example, you can specify that users must fill password in a password TextBox before submit the login form. You have to set two important properties when using the RequiredFieldValdiator control.

ControlToValidate: The ID of the control for which RequiredFieldValidator control will be associated.

ErrorMessage: This property is used to show the error message, if the user forget to enter the data, then custom error message will appear.

You have to set the above two given property in all the ASP.NET validation control. These two properties are common to all validation control except ValidationSummary control.

Example

<asp:TextBox ID="txtName"
runat="server"
Width="200px">
</asp:TextBox>          
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server"
ControlToValidate="txtName"
ErrorMessage="Enter Name"
ForeColor="Red">
</asp:RequiredFieldValidator>