Nikolaos Kantzelis ASP.Net Blog

This blog will focus on ASP.NET Framework

Sponsors

About Me

Great Blogs

ASP.Net validation controls

In this post I would like to continue talking about validation in ASP.Net applications. I will look into the validation controls that ASP.Net provides. You can have a look at the first post in my blog regarding validation.

You will show you that we can perform all our main validation tasks without almost writing any code. We will add validation to our form by adding one or more controls.We can also display messages to the user.

The controls I am going to look into are:

  • CompareValidator
  • CustomValidator
  • RangeValidator
  • RegularExpressionValidator
  • RequiredFieldValidator
  • ValidationSummary

We need to create the web form first. 

1) Launch Visual Studio 2010/2008/2005 (express editions will work fine). Create a new empty website and choose a suitable name for it. Choose c# as the development language.

2) Add a web form to your website. Leave the default name.

3) Then add a few textboxes in Default.aspx page. Create a table inside the form element and add textboxes for Name,Surname,Age,Email,Website,Password,Confirm Password,Comments.

Add a submit button as well.

The code inside the body element should be like this. if you do not want to type all that, then by all means just copy and paste it.

 

<body>
    <form id="form1" runat="server">
    <div>
    <p>Please note that all fields are mandatory</p>
     <table cellSpacing="2" cellPadding="2" width="400" border="1">
        <tr>
          <td>Name:</td>
          <td>
            <asp:TextBox id="txtName" runat="server"></asp:TextBox>
          </td>
        </tr>
        <tr>
          <td>Surname:</td>
          <td>
            <asp:TextBox id="txtSurname" runat="server"></asp:TextBox>
          </td>
            
        </tr>
        <tr>
          <td>Age:</td>
          <td>
<asp:TextBox id="txtAge" runat="server" Width="70px">
          </asp:TextBox>
          </td>
          
        </tr>
<tr>
          <td>Email:</td>
          <td>
            <asp:TextBox id="txtEmail" runat="server"></asp:TextBox>
          </td>
          
        </tr>

         <tr>
          <td>Web Site:</td>
          <td>
            <asp:TextBox id="txtSite" runat="server"></asp:TextBox>
          </td>
          
        </tr>
        <tr>
          <td>Password:</td>
          <td>
            <asp:TextBox id="txtPassword" TextMode="Password" runat="server">
            </asp:TextBox>           
          </td>            
          
        </tr>
        <tr>
          <td>Re-enter password:</td>
          <td>
<asp:TextBox id="txtconfPassword" runat="server" TextMode="Password">
</asp:TextBox></td>
          
           
        </tr>

          <tr>
          <td>Comments:</td>
          <td>
            <asp:TextBox id="txtcomments" runat="server" TextMode="MultiLine">
           </asp:TextBox></td>
          
            </td>
        </tr>
        <tr>
          <td></td>
          <td>
<asp:Button id="btnSubmit" runat="server" Text="Submit"
onclick="btnSubmit_Click">
       </asp:Button>
          </td>
          
        </tr>
      </table>
      
       
    </div>
    </form>
</body>

 

 4) The first requirement one should have when it comes to validating the form is "Not to leave any of the fields empty".

We will use the RequiredFieldValidator from the Validation web server controls in the Toolbox inside Visual Studio.

I will show you the RequiredFieldValidator for the first textbox txtName. It looks like this.

<asp:RequiredFieldValidator 
            ID="NameValidator" runat="server" 
            ErrorMessage="Please enter your name" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtName">
            </asp:RequiredFieldValidator>

 

The most important property is ControlToValidate="txtName" which ties the validation control with our textbox. Run your application and press the submit button. You will see the red "*" appearing.It is so simple.Note that there is no postback in the page.

We have client side validation out of the box.

Go to View->Source of the Html page and have a look at the Javascript generated for you by the runtime.

<script type="text/javascript">
//<![CDATA[
var NameValidator = document.all ? document.all["NameValidator"] : document.getElementById("NameValidator");
NameValidator.controltovalidate = "txtName";
NameValidator.errormessage = "Please enter your name";
NameValidator.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid";
NameValidator.initialvalue = "";
//]]>
</script>

While you are in the Source of the Html page, have a look on how the validator control renders. The RequiredFieldValidator for the Name field should look something like this.

 <span id="NameValidator" style="color:Red;font-weight:bold;visibility:hidden;">*</span>

 Note that it renders like a span element.

5) I will continue adding RequiredFieldValidator controls for the remaining fields.So the Default.aspx page should look something like this. I am adding only the code in the body element.

<body>
    <form id="form1" runat="server">
    <div>
    <p>Please note that all fields are mandatory</p>
     <table cellSpacing="2" cellPadding="2" width="400" border="1">
        <tr>
          <td>Name:</td>
          <td>
            <asp:TextBox id="txtName" runat="server"></asp:TextBox></td>
        <td>
            <asp:RequiredFieldValidator 
            ID="NameValidator" runat="server" 
            ErrorMessage="Please enter your name" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtName">
            </asp:RequiredFieldValidator>
            </td>
        </tr>

         <tr>
          <td>Surname:</td>
          <td>
            <asp:TextBox id="txtSurname" runat="server">
          </asp:TextBox></td>
              <td>
            <asp:RequiredFieldValidator 
            ID="SurnameValidator" runat="server" 
            ErrorMessage="Please enter your Surname" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtSurname">
            </asp:RequiredFieldValidator>
            </td> 
          
        </tr>
        <tr>
          <td>Age:</td>
          <td>
            <asp:TextBox id="txtAge" runat="server" Width="70px">
            </asp:TextBox></td>
           <td>
            <asp:RequiredFieldValidator 
            ID="AgeValidator" runat="server" 
            ErrorMessage="Please enter your Age" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtAge">
            </asp:RequiredFieldValidator>
            </td> 
        </tr>
        <tr>
          <td>Email:</td>
          <td>
            <asp:TextBox id="txtEmail" runat="server"></asp:TextBox></td>
            <td>
          <asp:RequiredFieldValidator 
            ID="EmailFieldValidator" runat="server" 
            ErrorMessage="Please enter your Email" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtEmail">
            </asp:RequiredFieldValidator>
            </td>
        </tr>

         <tr>
          <td>Web Site:</td>
          <td>
            <asp:TextBox id="txtSite" runat="server"></asp:TextBox></td>
           <td>
          <asp:RequiredFieldValidator 
            ID="SiteValidator" runat="server" 
            ErrorMessage="Please enter your Website URL" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtSite">
            </asp:RequiredFieldValidator>
            </td>
        </tr>
        <tr>
          <td>Password:</td>
          <td>
            <asp:TextBox id="txtPassword" TextMode="Password" runat="server">
          </asp:TextBox></td>    
           
            <td>
             <asp:RequiredFieldValidator 
            ID="PasswordValidator" runat="server" 
            ErrorMessage="Please enter the password" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtPassword">
            </asp:RequiredFieldValidator>
            
            </td>     
          
        </tr>
        <tr>
          <td>Re-enter password:</td>
          <td>
    <asp:TextBox id="txtconfPassword" runat="server" TextMode="Password">
          </asp:TextBox></td>
          
        </tr>

          <tr>
          <td>Comments:</td>
          <td>
    <asp:TextBox id="txtComments" runat="server" TextMode="MultiLine">
          </asp:TextBox></td>
           <td>
          <asp:RequiredFieldValidator 
            ID="CommentsValidator" runat="server" 
            ErrorMessage="Please enter your Comments" 
            Text="*" Font-Bold="True" 
            ForeColor="Red" ControlToValidate="txtComments">
            </asp:RequiredFieldValidator>
            </td>
            
        </tr>
        <tr>
          <td></td>
          <td>
<asp:Button id="btnSubmit" runat="server" Text="Submit" 
onclick="btnSubmit_Click">
</asp:Button></td>
          
        </tr>
      </table>     
    </div>
    </form>
</body>

 

 Run your application and try to submit the form without filling any of the fields.

6) Now I will also add a ValidationSummary control at the bottom of the table element. This is a very nice control that without any configuration connects and displays all the messages that are set in the

ErrorMessage property of all the validation controls.So I am going to add this control after the </table> tag.

 </table>
      
<asp:ValidationSummary ID="ValidationSummary" runat="server"
ShowMessageBox="true" DisplayMode="BulletList" HeaderText="Must be corrected" />
    </div>
    </form>
</body>

Run your application and see all the ErrorMessage values of all the validation controls appearing in the page and in the message box.

That is pretty impressive!!!

7) Now let's add some more validation controls in our form. Let's just say that for the Age field, we need to have a value that is obviously numeric and greater than 18.

We will place a CompareValidator on the form after the Age field. It should be something like this

 <td>
<asp:CompareValidator ID="AgeCompareValidator" runat="server" 
ErrorMessage="Must be greater than 18" ControlToValidate="txtAge" 
Font-Bold="True" Operator="GreaterThanEqual" Type="Integer"
ValueToCompare="18" ForeColor="Red">*</asp:CompareValidator>
</td>

Run your application, type a non-numeric value in the Age field or type a numeric value less than 18. In both cases the form will not validate.

8) Now let's add a new validation control that checks the email is valid. We will use a RegularExpressionValidator validation control.

The code for the email field will look like this

   
<td>
            
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" 
runat="server" ErrorMessage="Email is not valid!!!" 
ControlToValidate="txtEmail" Text="*" Font-Bold="true" ForeColor="Red" 
SetFocusOnError="True"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator>
            
</td>
      

You will see that we have a ValidationExpression property with a regular expression as a value and I added a new property SetFocusOnError which sets the focus on the control that is invalid.

Run your application and try to fill in the Email field with an invalid email address.The form will not validate.

9) We will add another RegularExpressionValidator validation control that validates the Web Site field.Run your application and try to fill in the Web Site field with an invalid URL.The form will not validate.

10) Now we will add a new field in our form. It will allow the user to enter a date (between 1/1/2011 and 31/12/2011) for a competition. We will add this Competition Date field immediately after Web Site field.

We will use a RangeValidator control.The markup should look like this:

<tr>
 <td>Competition Date:</td>
 <td>
 <asp:TextBox id="txtCompetition" runat="server"></asp:TextBox></td>
 <td>
 <asp:RequiredFieldValidator 
 ID="CompetitionRequiredFieldValidator" runat="server" 
 ErrorMessage="Please enter the Competition Field" 
 Text="*" Font-Bold="True" 
 ForeColor="Red" ControlToValidate="txtCompetition" SetFocusOnError="true">
 </asp:RequiredFieldValidator>
 </td>
 <td>
 <asp:RangeValidator ID="CompetitionRangeValidator" 
 runat="server" 
 ErrorMessage="Invalid Date" ForeColor="Red" Font-Bold="true" Text="*" 
 SetFocusOnError="true" ControlToValidate="txtCompetition" 
 MaximumValue="2011-12-31" MinimumValue="2011-01-01" Type="Date">
</asp:RangeValidator>
            
</td>

</tr>

Run your application and try to fill in the Competition Date field with an invalid date.The form will not validate.

11)  We will add another field in our form. We will call it the UserName field. The user must enter a username. We will use this field to highlight the last validation control, CustomValidator.

 There is a custom validation requirement. The username must be between 6 and 12 characters.

The CustomValidator control allows us to write a method to handle the validation of the value entered. We can write a Javascript validation function to perform validation on the client side and perform validation on the server side by writing code in the code behind file.

So, the markup looks like this.

  <tr>
      <td>UserName:</td>
      <td>
     <asp:TextBox id="txtUsername" runat="server"></asp:TextBox></td>
      <td>
      <asp:RequiredFieldValidator 
      ID="UsernameRequiredFieldValidator" runat="server" 
      ErrorMessage="Please enter your Username" 
      Text="*" Font-Bold="True" 
      ForeColor="Red" ControlToValidate="txtUsername" SetFocusOnError="true">
            </asp:RequiredFieldValidator>
            </td>
            <td>
                <asp:CustomValidator 
                ID="UserNameCustomValidator" 
                runat="server" 
                ErrorMessage="UserName must be between 6 and 12 characters"
                Font-Bold="True"
                ForeColor="Red" 
                Text="*" 
                SetFocusOnError="true"
                ControlToValidate="txtUserName" 
                ClientValidationFunction="CheckUserName" 
                 OnServerValidate="ValidateUserName"
                  ></asp:CustomValidator>
            
            </td>

        </tr>

Note the  ClientValidationFunction="CheckUserName" OnServerValidate="ValidateUserName".

We will have to create a Javascript function CheckUserName and a method in the code behind file called ValidateUserName.

The Javascript function should look like this (place this snippet inside the head element)

<head runat="server">
    <title>Submission Form</title>
    <script type="text/javascript">
    function CheckUserName(source,args)
    {
        var myString = args.Value;

        var length = myString.length;

        if (length < 6 || length > 12)


    args.IsValid=false;
   else
    args.IsValid=true;
   }
</script>  
    
    
</head>

The javascript code above is very easy to understand.I check for the length of the value in the field and I set the IsValid property of the field value to false if the field contains less than 6 or more than 12 characters.

This will trigger the ErrorMessage property of the CustomValidator control and the appropriate message will be printed out in the screen. If this is not the case the validation will pass.

Now we must implement the ValidateUserName routine.In the code behind file you could have something like this.

protected void ValidateUserName(object source,ServerValidateEventArgs e)
    {

        e.IsValid = false;

        try
        {
            string username = e.Value;

            if (username.Length > 6 && username.Length < 12)
                { 

                
                e.IsValid = true;
                 }
        }

        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
       
         
        
    }

The code above is very easy to follow.I check the IsValid property of the Value passed for validation.

The IsValid property gets whether the value specified by the Value property passed validation. If the field value contains less than 6 or more than 12 characters then the ErrorMessage property of the CustomValidator control will be triggered and the appropriate message will be printed out in the screen. If this is not the case the validation will pass.

I want to mention again how important is to have validation on the server.

Run your application and fill in the form correctly. Type less than 6 characters in the username field. You will get a validation error. Now type more than 6 characters in the username field.

The validation will succeed.

12) We want to transfer the form data into another page. Add another page in the web site. Name it Submitted.aspx .

The markup for this page should be like this

<body>
    <form id="form1" runat="server">
    <div>
    <asp:Label ID="lblName" runat="server" Text="Label"></asp:Label>
    <br />

     <asp:Label ID="lblSurname" runat="server" Text="Label"></asp:Label>
    <br />
     <asp:Label ID="lblAge" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="lblEmail" runat="server" Text="Label"></asp:Label>
    <br />

     <asp:Label ID="lblWebsite" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="lblcompetition" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="lblusername" runat="server" Text="Label"></asp:Label>
    <br />
    <asp:Label ID="lblcomments" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>

 

In the code behind file in the Page_Load event handling routine type

 Response.Write("Thank you for filling in the form.");
            Response.Write("<br/>");

TextBox text1 = this.PreviousPage.FindControl("txtName"as TextBox;
TextBox text2 = this.PreviousPage.FindControl("txtSurname"as TextBox;
TextBox text3 = this.PreviousPage.FindControl("txtAge"as TextBox;
TextBox text4 = this.PreviousPage.FindControl("txtEmail"as TextBox;
TextBox text5 = this.PreviousPage.FindControl("txtSite"as TextBox;
TextBox text6 = this.PreviousPage.FindControl("txtCompetition"as TextBox;
TextBox text7 = this.PreviousPage.FindControl("txtUsername"as TextBox;
TextBox text8 = this.PreviousPage.FindControl("txtComments"as TextBox;
lblName.Text = text1.Text;
lblSurname.Text = text2.Text;
lblAge.Text = text3.Text;
lblEmail.Text = text4.Text;
lblWebsite.Text = text5.Text;
lblcompetition.Text = text6.Text;
lblusername.Text = text7.Text;
lblcomments.Text = text8.Text;

 In the default.aspx page set the PostBackUrl property of the button to the Submitted.aspx.

If you want to learn more about cross page posting have a look at this post of mine.

Run your application, fill in all the form fields correctly and hit the Submit button. You will be transferred to the Submitted.aspx page.

Please note that many controls support validation. Both server controls and HTML controls. DropDownList,ListBox,RadioButtonList can work with validation controls.

HTMLInputText,HTMLTextArea,HTMLSelect,HTMLInputFile controls can work with validation controls.

Another important thing to know is that the validation that takes place on the server side takes place after the Page_Load event being fired.We could have used a different approach to validate the data on the server side.

We could check for valid data in the Page_Load event handling routine.

So if we have this snippet of code

protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            
            if (this.IsValid)
            {
                //more code
            }
        }
    }

 

This will fail. The error will be something like this


"Page.IsValid cannot be called before validation has taken place. It should be queried in the event handler for a control that has CausesValidation=True and initiated the postback, or after a call to Page.Validate.
"

So if we want to check the IsValid property of the Page we must call the Validate() method on the page

if (IsPostBack)
        {
            this.Validate();
            if (this.IsValid)
            {
                
            }
        }

This will not fail. Comment out everything you have in the Page_Load event handling routine.

I understand that this is a very long post. I hope it makes sense. I am sure that if you follow all the steps you will get a good grasp of validation and validation controls.

Drop me an email if you want the source code.

Hope it helps!!!!

Comments

oghanim said:

Thanks,

appreciate sending source.

oghanim@hotmail.com

# February 24, 2011 7:02 PM

sildenafil said:

Do you have any more info on this?

# March 26, 2011 6:37 AM

tips said:

That was a truly incredible writing.

# November 12, 2011 5:35 PM

gotibandhu said:

Very informative post. It's really helpful for me and helped me lot to complete my task. Thanks for sharing with us. I had found another nice post over the internet which was also explained very well about Validating FileUpload control for specific file type and required field, for more details of this post check out this link...

mindstick.com/.../default.aspx.

Thanks

# January 9, 2012 4:54 AM

Waddell said:

Well written post. Highly recommended.

# February 4, 2013 10:36 AM