Banner Ad

Friday, January 4, 2013

Validators in ASP.Net - Part 1

By Francis   Posted at   9:00 AM   Validators in ASP.Net

For any application, validation performs a key role. For this Microsoft provides the following types of validators:
1. Required Field validator
2. Regular Expression Validator
3. Range Validator
4. Compare Validator
5. Custom Validator
6. Validation Summary

 In this article, we are going to see about Required Field Validator. Add a new Page using Right click on Solution on the context Menu choose Add  New Item and select the “Web Form.aspx”.
After that add the below code in the aspx file.
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="ValidatorDemo.aspx.vb"
    Inherits="AllInOne.ValidatorDemo" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    Enter Name:
                </td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ControlToValidate="txtName" ErrorMessage="Name Required"  SetFocusOnError="true" 
                        runat="server"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td colspan="3">
                    <asp:Button runat="server" Text="Click Me!" />
                </td>
            </tr>
        </table>
    </div>
    </form>
</body>
</html>

Explanation: In the above code, the declarative sentence adds the required field validator:
                    <asp:RequiredFieldValidator ControlToValidate="txtName" ErrorMessage="Name Required"  SetFocusOnError="true" runat="server"></asp:RequiredFieldValidator>

I’m going to explain the each and every attribute in the above code. It’s a mandatory rule, that every asp.net control must start with “asp” tag.
Attribute
Description
runat
This is the server control, which is processed by the WEB Server (IIS). So this is the required attribute for every server control.
Control ToValidate
This attribute is used to denote which control we need to validate.  In this example, we give the ID of the name text box “txtName”.
ErrorMessage
Used to give the Error message, when validation fails.
What is exactly happen when the validator added in the web page? How its process the validation? The answer is simple, since it’s a server control so the server process it and emulate/added the necessary javascript. This can be noted, when the page’s source found thru “view source” option.
Happy Programming!!!

About Francis

Francis, an Associate at Cognizant. Having 7+ Years of experience in Microsoft web technologies.

Connect with Us