Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

ASP.NET the validator


May 13, 2021 ASP.NET


Table of contents


The validator

ASP.NET controls are to validate user-entered data to ensure that useless, unauthorized, contradictory data cannot be stored.

ASP.NET provides validation controls in the following areas:

  • Required Field Validator
  • RangeValidator
  • CompareValidator
  • Regular Expression Validator
  • Custom Authenticator
  • Validation Summary Control (Validation Summary)

BaseValidator class

Validated classes inherit from the BaseValidator class, so they inherit its properties and methods. T herefore, learning the properties and methods of this basic class, which is the basis for all effectiveness controls, will be of great help for subsequent learning:

Part Describe
ControlToValidate Gets or sets the input controls to validate.
Display Explains how the error prompt appears.
EnableClientScript Explains whether the client has taken validation.
Enabled Turn the authenticator on or off.
ErrorMessage Explains the error string.
Text The text that will be displayed if validation fails.
IsValid Explains whether the control value is valid.
SetFocusOnError Whether to set the focus to the relevant input control when validation fails.
ValidationGroup Gets or sets the name of the validation group to which this validation control belongs.
Validate Validate the associated input controls and update the IsValid property.

Required FieldValidator control

The Required FieldValidator control ensures that the required fields are not empty. I t is primarily tied to the text box so that the user enters it.

The syntax of this control is as follows:

<asp:RequiredFieldValidator ID="rfvcandidate" 
   runat="server" ControlToValidate ="ddlcandidate"
   ErrorMessage="Please choose a candidate" 
   InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

RangeValidator control

The RangeValidator control is responsible for verifying that the value entered is within the preset range.

It has three specific properties:

Property Describe
Type It defines the data type. A vailable data types include: Currency, Date,
Double, Integer, and String
Min (MinimumValue) It specifies the minimum value in the range
Maximum Value (MaximumValue) It specifies the maximum value in the range

The syntax of this control is as follows:

<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass" 
   ErrorMessage="Enter your class (6 - 12)" MaximumValue="12" 
   MinimumValue="6" Type="Integer">

</asp:RangeValidator>

CompareValidator control

The CompareValidator control validates the value based on the value entered into another input control, the constant value, or the correct data type.

It has the following specific properties:

Property Describe
Type It defines the data type.
ControlToCompare It specifies the values that need to be compared in the input control.
ValueToCompare It specifies the value that remains unchanged in the input control.
Operator It specifies the operator of the comparison, and the available values include equal, unequal, greater than or equal, less than, less than or equal, and data type checking.

The basic syntax of this control is as follows:

<asp:CompareValidator ID="CompareValidator1" runat="server" 
   ErrorMessage="CompareValidator">

</asp:CompareValidator>

RegularExpressionValidator control

The RegularExpressionValidator control allows you to determine the validity of your input by matching regular expressions. R egular expressions are set in the properties of ValidationExpression.

The following table summarizes the syntax structure that regular expressions typically use:

Escape characters Describe
\b Matches the backbar.
\t and tab match.
\r Matches the enter key.
\v Matches vertical tabs.
\f matches the page break.
\n matches the line change.
\ Escape character.

In addition to simple character matching, a class of characters can be set to match, called wildcards.

Wildcard Describe
. You can match any character except .
[abcd] You can match any character in a collection.
[^abcd] Exclude any character in the collection.
[2-7a-mA-M] Matches any character in a specific range.
\w Matches any alphanumeric character group and underscore.
\W Matches any non-word characters.
\s Matches characters such as spaces, watch positions, line changes, etc.
\S Matches any characters that are not spaces.
\d Matches any number of characters.
\D Matches any non-minor characters.

A quantum word can indicate a specific number of words that appear in a character.

Quantifiers Describe
* Zero or more matches.
+ One or more matches.
? Zero or one match.
{N} N match.
{N,} N or more matches.
{N,M} Matches between N and M.

The basic syntax of the control is as follows:

<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
   ValidationExpression="string" ValidationGroup="string">

</asp:RegularExpressionValidator>

CustomValidator control

The CustomValidator control allows client- and server-specific validation routines to be written to validate values.

Client authentication is done appropriately through ClientValidationFunction. C lient validation routines should be written in a scripting language recognized by the browser, such as JavaScript or VBScript.

The server-side validation routine should be generated by the control's ServerValidate event processor. T he server-side validation routine should be written in any .Net language, such as C# VB.Net.

The basic syntax of this control is as follows:

<asp:CustomValidator ID="CustomValidator1" runat="server" 
   ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">

</asp:CustomValidator>

Validation Summary control

The ValidationSummary control does not perform any validation but displays a summary of all errors on the page. T his summary shows the value of the error message property for all failed validation controls.

The following two lists of properties that are mutually contained are listed for error messages:

  • ShowSummary: Display error messages in a special format.
  • ShowMessageBox: Display the error message in a separate window.

The basic syntax of this control is as follows:

<asp:ValidationSummary ID="ValidationSummary1" runat="server" 
   DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />

The validation group

Complex pages have different groups of information at different levels. I n this case, different groups will have different validations, which can be resolved by the validation groups.

To create a validation group, you must place them in the same logical group by setting the ValidationGroup properties of the input control and the validation control.

Example

The following example describes a form to be filled out by students across the school, which is divided into four parts for running for president. H ere, we'll use validation controls to verify what the user entered.

This is in the form of a design view:

ASP.NET the validator

Here's the code for this section:

<form id="form1" runat="server">

   <table style="width: 66%;">

      <tr>
         <td class="style1" colspan="3" align="center">
         <asp:Label ID="lblmsg" 
            Text="President Election Form : Choose your president" 
            runat="server" />
         </td>
      </tr>

      <tr>
         <td class="style3">
            Candidate:
         </td>

         <td class="style2">
            <asp:DropDownList ID="ddlcandidate" runat="server"  style="width:239px">
               <asp:ListItem>Please Choose a Candidate</asp:ListItem>
               <asp:ListItem>M H Kabir</asp:ListItem>
               <asp:ListItem>Steve Taylor</asp:ListItem>
               <asp:ListItem>John Abraham</asp:ListItem>
               <asp:ListItem>Venus Williams</asp:ListItem>
            </asp:DropDownList>
         </td>

         <td>
            <asp:RequiredFieldValidator ID="rfvcandidate" 
               runat="server" ControlToValidate ="ddlcandidate"
               ErrorMessage="Please choose a candidate" 
               InitialValue="Please choose a candidate">
            </asp:RequiredFieldValidator>
         </td>
      </tr>

      <tr>
         <td class="style3">
            House:
         </td>

         <td class="style2">
            <asp:RadioButtonList ID="rblhouse" runat="server" RepeatLayout="Flow">
               <asp:ListItem>Red</asp:ListItem>
               <asp:ListItem>Blue</asp:ListItem>
               <asp:ListItem>Yellow</asp:ListItem>
               <asp:ListItem>Green</asp:ListItem>
            </asp:RadioButtonList>
         </td>

         <td>
            <asp:RequiredFieldValidator ID="rfvhouse" runat="server" 
               ControlToValidate="rblhouse" ErrorMessage="Enter your house name" >
            </asp:RequiredFieldValidator>
            <br />
         </td>
      </tr>

      <tr>
         <td class="style3">
            Class:
         </td>

         <td class="style2">
            <asp:TextBox ID="txtclass" runat="server"></asp:TextBox>
         </td>

         <td>
            <asp:RangeValidator ID="rvclass" 
               runat="server" ControlToValidate="txtclass" 
               ErrorMessage="Enter your class (6 - 12)" MaximumValue="12" 
               MinimumValue="6" Type="Integer">
            </asp:RangeValidator>
         </td>
      </tr>

      <tr>
         <td class="style3">
            Email:
         </td>

         <td class="style2">
            <asp:TextBox ID="txtemail" runat="server" style="width:250px">
            </asp:TextBox>
         </td>

         <td>
            <asp:RegularExpressionValidator ID="remail" runat="server" 
               ControlToValidate="txtemail" ErrorMessage="Enter your email" 
               ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
            </asp:RegularExpressionValidator>
         </td>
      </tr>

      <tr>
         <td class="style3" align="center" colspan="3">
            <asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click" 
               style="text-align: center" Text="Submit" style="width:140px" />
         </td>
      </tr>
   </table>
   <asp:ValidationSummary ID="ValidationSummary1" runat="server" 
      DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />
</form>

The code for the submit button is as follows:

protected void btnsubmit_Click(object sender, EventArgs e)
{
   if (Page.IsValid)
   {
      lblmsg.Text = "Thank You";
   }
   else
   {
      lblmsg.Text = "Fill up all the fields";
   }
}

Related articles

ASP.NET rangeValidator control