Friday, February 11, 2011

Form Validation

ASP.NET makes it really simple, maybe to simple, to add form validation to your web forms. Suppose we had a simple form that consisted of these fields:


  • First Name
  • Last Name
  • Email Address
The code for such a form would probably resemble this:

  1.  <form id="simpleForm" runat="server">
  2.     <div>
  3.    
  4.         First Name:<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
  5.         <br />
  6.         Last Name:<asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
  7.         <br />
  8.         Email Address:<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
  9.         <br />
  10.        
  11.     </div>
  12.  </form>

After we add our validation controls, which you can add from the "Validation" tab of the Toolbox, the code looks like this:

  1.     <form id="signUp" runat="server">
  2.     <div style="width: 957px">
  3.    
  4.         First Name:<asp:TextBox ID="txtFName" runat="server"></asp:TextBox>
  5.         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
  6.             ControlToValidate="txtFName" ErrorMessage="First Name Required"></asp:RequiredFieldValidator>
  7.         <br />
  8.         Last Name:<asp:TextBox ID="txtLName" runat="server"></asp:TextBox>
  9.         <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
  10.             ControlToValidate="txtLName" ErrorMessage="Last Name Required"></asp:RequiredFieldValidator>
  11.         <br />
  12.         Email Address:<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>
  13.         <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
  14.             ControlToValidate="txtEmail" ErrorMessage="Enter a vaild email address"
  15.             ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>
  16.         <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
  17.             ControlToValidate="txtEmail" ErrorMessage="Email address required"></asp:RequiredFieldValidator>
  18.         <br />
  19.        
  20.     </div>
  21.     </form>

And what will happen now is our web form will make the First Name, Last Name and email fields required, as well as validate that the email address is really an email address.

No comments:

Post a Comment

I Break Code Where code gets done.
ASP.NET | HTML | SQL Server | VB.NET | Request A Topic |