A simple example of validation in ASP.Net applications

I am going to start a new series of posts and I am going to cover in depth all the validation mechanisms/techniques/controls we have available in our ASP.Net applications.

As many of you may know, I am a Microsoft Certified Trainer and I will present this series of posts from a trainer's point of view. This series of posts will be helpful to all of novice/intermediate programmers who want to see all the tools available for validating data in ASP.Net applications.

I am not going to try to convince you why we need to validate our data because the reasons for doing so are profound.

So if you do not know much about the subject of validation in ASP.Net applications,  read on. I will be looking forward to your feedback/comments.

I will keep the same format in my posts. I will use hands on examples that everyone can follow.

I am going to cover client-side validation with JavaScript and also cover server side validation. We will also cover validation architecture and validation controls.

Let's see an example of form validation. Every time someone submits data to our server through a web form we must check for various conditions, e.g

  • All fields that are mandatory should be filled
  • Email fields should have appropriate checks
  • Passwords should match
  • Phone numbers should be checked (e.g only numeric data with exactly ten digits)

We will use client side validation and server side validation.You must be careful and do not make the mistake to have only client side validation. You must always validate your data on server side. In fact you should use both client side and server side validation. It is not very difficult to bypass client side validation.

With client side validation we can reduce unnecessary round trips to server. By that we make our application more responsive and the user will get immediate feedback.

We will start with an example of client side validation. It will be very easy and we will just check if some fields are left blank or not.We will start with a simple Html page.

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) Add a html page to your site.I named it Validation.htm. We will add 3 texboxes and a button inside the form element.

4) Inside my body tags I have something like this

 

<body>
<form name="login" method="post" onsubmit="return ValidateForm()">
<table cellspacing="2" cellpadding="2" border="1">
<tr><td align="right"><b>Name:</b></td>
  <td><input id="name" /></td>
  </tr>
<tr><td align="right"><b>E-mail:</b></td>
  <td><input id="email" /></td>
 </tr>
      <tr><td align="right"><b>Age:</b></td>
  <td><input id="age" /></td>
 </tr>
</table>
<input type="submit" value="Click Me!!!" />
</form>

</body> 

5) This is very straight forward. Anyone with basic HTML skills can accomplish that. I am going to add some <span> elements next to each textbox. You will see why I need them later on.

 My code inside the body element looks like this

<body>
<form name="login" method="post" onsubmit="return ValidateForm()">
<table cellspacing="2" cellpadding="2" border="1">
<tr><td align="right"><b>Name:</b></td>
  <td><input id="name" /></td>
  <td><span id="error_name" 
            style="visibility:hidden;color:red">
      Mandatory field</span></td></tr>
<tr><td align="right"><b>E-mail:</b></td>
  <td><input id="email" /></td>
  <td><span id="error_email" 
            style="visibility:hidden;color:red">
      Mandatory field</span></td></tr>
      <tr><td align="right"><b>Age:</b></td>
  <td><input id="age" /></td>
  <td><span id="error_age" 
            style="visibility:hidden;color:red">
      Mandatory field</span></td></tr>
</table>
<input type="submit" value="Click Me!!!" />
</form>

</body>

6) I have a new column added next to each textbox. For the Name textbox I add

<td><span id="error_name" 
            style="visibility:hidden;color:red">
      Mandatory field</span></td>

It is basically a span element with some style that keeps the words "Mandatory field" hidden when the page is loaded.So there will be no error messages when the page is loaded.

7) Inside the head element of the html page we need to add some Javascript code.

 <script type="text/javascript">
        function ValidateForm() {
            var ret = false;
            if (document.all["name"].value == "")
                document.all["error_name"].style.visibility = "visible";
            else if (document.all["email"].value == "")
                document.all["error_email"].style.visibility = "visible";
            else if (document.all["age"].value == "")
                document.all["error_age"].style.visibility = "visible";
            else
                ret = true;
            return ret;
        }
    </script>

 

8) I am not going to go explain in detail what is happening here. If you need to learn JavaScript the best place on the web is W3schools. I have a Javascript function and I check if the fields are empty when the form is submitted. If this is the case for any of the fields a red status with the words "Mandatory field" appears to the user.

9) Run your application and check it out yourself.

10) As it was stated previously we also need to have server side validation.The data is actually used in the server and if errors occur they should be posted back to the user so he can correct them.

11) In your Default.aspx page add 3 label controls and 3 textbox controls. The code inside the body element should be something like this.

 

<body>
    <form id="form1" runat="server">
    <div>
    <table cellSpacing="2" cellPadding="2" width="250" border="2">
        <tr>
          <td>Name:</td>
          <td>
            <asp:TextBox id="txtname" runat="server"></asp:TextBox></td>
          <td>
              <asp:Label ID="lblname" runat="server" ForeColor="Red" />
          </td>
        </tr>        
        <tr>
          <td>Email:</td>
          <td>
            <asp:TextBox id="txtemail" runat="server"></asp:TextBox></td>
          <td>
              <asp:Label ID="lblemail" runat="server" ForeColor="Red" />
          </td>
        </tr>
         <tr>
          <td>Age:</td>
          <td>
            <asp:TextBox id="txtage" runat="server"></asp:TextBox></td>
          <td>
              <asp:Label ID="lblage" runat="server" ForeColor="Red" />
          </td>
        </tr>
        <tr>
            <td>
                <asp:Button ID="btnSub" runat="server" Text="Submit" 
                    />
            </td>
        </tr>
    </table>
    </div>
    </form>
</body>

 

So we have 3 textboxes (Name,Email,Age,) that we want to fill in with data and perform some sort of server side validation. The 3 labels will appear with appropriate instructions if the fields are not filled in with any data.

12) Double click on the button. In the button event handling routine type

 

        if (txtname.Text == "")
            lblname.Text = "Please fill in your name";
        else
            lblname.Text = "";

        if (txtemail.Text == "")
            lblemail.Text = "Please fill in your email";
        else
            lblemail.Text = "";

        if (txtage.Text == "")
            lblage.Text = "Please fill in your age";
        else
            lblage.Text = "";

        if (txtname.Text != "" &&
            txtemail.Text != "" &&
            txtage.Text != "")
        {

            Response.Write("All fields were filled in!!!1");

        }

There is nothing difficult in this code. Some simple IF statements that check the Text properties of the Textboxes and set the Label controls text values accordingly.

13) Run your application. Leave any of the fields empty and hit the button. See the error messages printed out in the screen. Fill in all the fields and check again the message printed out in the screen.

In my next post I will look into ASP.Net Validation framework features. We will see how easy it is to perform validations.

Hope it helps.

3 Comments

Comments have been disabled for this content.