ASP.NET Validation Controls

In every application development project, validation plays a very important role.

What exactly does validation mean?

It means checking user input for validity, or in short, checking user input for the input that is actually required or checking user input for improper values.

Types of validations

Normally in ASP.Net we may have 2 kinds of validations:

  1. Client Side - Here validation will be performed using client side scripts like JavaScript.
     
    • Advantage - Script execution is done at client side as it's an interpreted language so response is decreased, providing a good UI experience.
    • Disadvantages - No guarantee of support for these scripts at client side, or in some browsers there is an option to disable such scripts.
       
  2. Server Side - Here validation is performed using server side scripts like C#, VB.Net etc.
     
    • Advantage - No requirement from the client machine since all execution is done at the server side, so it considered to be safer compared to the client side.
    • Disadvantage - This kind of validation requires a trip to the server and back, so the performance is low compared to client Side.

ASP.Net Validation Controls

  • ASP.Net provides a set of validation controls featuring Rapid Application Development because of their easy-of-use and extensible features.
  • They provide both client side and server side validation. That's why the user will not need to wait for a full page postback to occur only to discover that they have failed to fill out your form completely, he/she will be notified immediately. And in case the client side fails to validate (because JavaScript is disabled or not supported) server side is always there and we can check the validity of the page using the IsValid property.

Types of validation controls

There are 6 validation controls provided by ASP.Net; they are:

  1. Required Field Validator
  2. Regular Expression Validator
  3. Compare Validator
  4. Range Validator
  5. Custom Validator
  6. Validation Summary

How to use?

Every Validation Control has some common properties; they are:

  • ControlToValidate - Control to be validated for proper input.
  • ErrorMessage and Text - Message/Text shown when validation fails (the difference will be discussed later)
  • Display - Values include None/Static/dynamic
    • none - The validation message is never displayed inline.
    • Static Space for the validation message is allocated in the page layout.
    • Dynamic Space for the validation message is dynamically added to the page if validation fails.
  • ValidationGroup - Using this property we can assign every validation control to a group.
    Example:
    • Consider our screen has the two input forms:
    • One where we input employee information and click on SaveCustomer
    • Another where we input supplier information and click on SaveSupplier.
    • Now the main concern is that we want both forms to be validated but only on respective button click,
    • so we just put ValidationGroup as "Customer" to all controls belonging to Customer and to Save Customer Button.
    • (Similarly "supplier"for Supplier controls and button).
  • SetFocusOnError - Decides whether focus is set to the control specified by the ControlToValidate property when validation fails.
    (In case multiple input controls fail validation, first control will get the focus)
  • EnableClientScript - Specifies whether clientside validation is enabled or not.

Let's discuss about each and every control in depth.

  1. RequiredFieldValidator
     
    • This control has a property called InitialText which can be set to any string value.
    • Input control fails validation if its value matches to this value.
    • By Default it's empty so it can be used for empty validation.
       
  2. RangeValidator
     
    • This control has three properties called Type, MinimumValue and MaximumValue.
    • Type can be set to one of the values string, Date, Currency, Integer and double and other two can be set to any values based on Type specified.
    • Input control fails validation when its value doesn't fall within the boundary of minimum and maximum value.

    Note: The Range Validator throws an exception if the values specified by MinimumValue and MaximumValue cannot be converted to the type provided by the Type Property.
     

  3. CompareValidator This validator control is useful in the 3 scenarios:
     
    • We want to compare a value of an input control with a value of other input control.
    • We want to compare a value of an input control with a constant value.
    • We want compare type of value of an input control.
       
    It has properties like:
     
    • Operator - specifies the type of comparison to be performed; possible values are:
       
      1. Equal
      2. GreaterThan
      3. GreaterThanEqual
      4. LessThan
      5. LessThanEqual
      6. NotEqual
      7. DataTypeCheck
         
    • Type - When the Operator is set to DataTypeCheck then the input control will be validated for the type of its value (which means it fails if conversion to the type specified by the Type property is not possible).

      Possible values are:
       
      1. Currency
      2. Date
      3. Integer
      4. String
         
    • ValueToCompare - A value to compare with.
    • ControlToCompare - Name of the control to compare with.
      • RegularExpressionValidator It has a property called ValidationExpression which can be set to any valid regular expression, and input control fails validation if it doesn't match this pattern.

        Note:RangeValidator,CompareValidator, RegularExpressionValidator will not validate for empty values..

      • CustomValidator It's the one of the most important validator.
        • It has a property called ClientValidationFunction which can be set to a name of the client-side validation script function used for validating user input.
        • An Event OnServerValidate will be used for Server Side Validation.
        • Unlike other Validation controls it has an automatic validation for empty value, for that it's required to set ValidateEmptyText property to true.
      • ValidationSummary
        • The ValidationSummary control is used to display a summary of all validation errors occurred in a group.
        • It has properties DisplayMode - Possible values are BulletList List SingleParagraph.
        • ShowMessageBox specifies whether the summary should be displayed in a message box or not
        • ShowSummary specifies whether the ValidationSummary control should be displayed or hidden

        Note:ErrorMessage property of validation control is used by ValidationSummary and the text is just displayed in place where validation control is placed (if validation fails).

How to explicitly make validators to run?

In server side we have Page.Validate() and in ClientSide we have the Page_ClientValidate() function.
(Both of them have overloads accepting validation group).

Example: Page.Validate("Customer");//In Server Side
ClientValidate("Supplier");//In Client Side

How to disable validations?

In server side we can simply do this by using the Enabled Property.

And in client side we have ValidatorEnable function which accepts two parameters Valdation control and Boolean value indicating enable/disable.

Example: ReqCustomerName.Enable=false;//In Server Side
ValidatorEnable(document.getElementById('ReqCustomerName'),false);//In Client Side

Go through the sample application once to get a better idea.

Hope you enjoyed the article. Keep Programming.

Up Next
    Ebook Download
    View all
    Learn
    View all