CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Using the Validator Controls in ASP.Net Projects

By Bala Murugan
Posted On May 27,2009
Article Rating:
Be first to rate
this article.
No of Comments: 0
Category: ASP.Net
Print this article.

Using the Validator Controls in ASP.Net Projects

 

Input validation is one of the important things we should implement in any project. From ASP days, we write our validation code using javascript wherever necessary. With the introduction of .Netframework, we have set of inbuilt validation controls which help in validating our inputs easily and which take very less time when compared to ASP days. Microsoft have identified some frequently done input validations and designed a set of validation controls which will do our input validations automatically when configured with the corresponding input controls. We will see about these validator controls and how to use these inbuilt validation controls in ASP.Net projects.

Below are the set of validation control that are packed with the ASP.Net.

Ø       RequiredFieldValidator control

Ø       RegularExpressionValidator control

Ø       RangeValidator control

Ø       CompareValidator control

Ø       CustomValidator control

Ø       ValidationSummary control

 

How these Validator control work?

To make this validation control to work, asp.net will render a javascript file that contains the validation scripts to client side when the page is rendered. From ASP.Net 2.0, these inbuilt validation script will be rendered using WebResource.axd handler due to some security reasons. In 1.x days, these will be rendered as a javascript file "WebUIValidation.js" and it will be referred in the page using the script tag.

 

Let us see about these validation controls in coming sections of this article.

 

RequiredFieldValidator control

As the name suggests, this control is used to do the mandatory check of a field in ASP.Net. For example, in an input entry form to make a name as mandatory we can use this control. Using this control is pretty simple.

Refer the below code,

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

                        ControlToValidate="txtName" ErrorMessage="Name is mandatory."></asp:RequiredFieldValidator>

 

Using the RequiredFieldValidator to validate a DropDownList is bit different when compared to TextBox control. The below code does that.

<asp:DropDownList ID="ddlCountry" runat="server">

            <asp:ListItem>Select</asp:ListItem>

            <asp:ListItem>India</asp:ListItem>

            <asp:ListItem>US</asp:ListItem>

            <asp:ListItem>UK</asp:ListItem>

        </asp:DropDownList>

        <asp:RequiredFieldValidator ID="RequiredFieldValidator1"

         InitialValue="Select" runat="server"

         ControlToValidate="ddlCountry"

         ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>

 

The only difference is we need to set the InitialValue property of the validator control to the default selected value of the DropDownList.

 

RegularExpressionValidator control

Sometimes, we may require validating inputs based on some patterns i.e. the input should be in particular format. For example, date format validations, email format, etc. These types of validations can be done using regular expression and javascript in ASP days. In ASP.Net, we can use the RegularExpressionValidator control which accepts a regular expression to validate the input.

Refer the below code.

<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

                    <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"

                        ControlToValidate="txtEmail" ErrorMessage="Please enter a valid email"

                        ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>

 

When we use Visual Studio, there are some predefined validation expressions available for the most often used input patterns like email, web address, PIN code, etc. Refer the below figure.

 

 

Click the button you find ValidationExpression property in property window of Visual studio to enable above dialog.

 

RangeValidator control

This validator control will help us to validate an input control to accept the value which should fall in a particular range. For example, if we want to restrict age textbox to fall within a range 1 to 100.

Refer the below code,

  <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>                   

  <asp:RangeValidator ID="RangeValidator1" runat="server"

     ControlToValidate="txtAge" ErrorMessage="Age Cannot be more than 100"

     MaximumValue="100" MinimumValue="1" Type="Integer"></asp:RangeValidator>

 

To make the validator work we need to set a property called Type(for specifying the type of the input).

 

CompareValidator control

This validator control will help us to compare the input in 2 input controls for a match like equal, less than, greater than, etc.  For example, password and confirm password field match.

To validate a email and confirm email field to have same email typed by the user,

 <asp:TextBox ID="txtEmail" runat="server"></asp:TextBox>

<asp:TextBox ID="txtConfirmEmail" runat="server"></asp:TextBox>

  <asp:CompareValidator ID="CompareValidator2" runat="server"

  ControlToCompare="txtEmail" ControlToValidate="txtConfirmEmail"

  ErrorMessage="Emails not matching"></asp:CompareValidator>

 




CustomValidator control

The validator controls provided by Microsoft will not satisfy all our validation needs. At times, we need to write our own validation functions and attach to an input control. Understanding this need Microsoft has provided us a CustomValidator control which can take a javascript validation method. We can also do a server side validation using this control.

 

Using Server side validation

For example, if we want to check if a website typed is alive or not we can use custom validator control and alert the user.

<asp:TextBox ID="txtWebsite" runat="server"></asp:TextBox>

                    <asp:CustomValidator ID="CustomValidator1" runat="server"

                        ControlToValidate="txtWebsite"

                        ErrorMessage="Your Website if not alive.Please enter a valid one."

                        onservervalidate="WebValidate"></asp:CustomValidator>

 

 protected void WebValidate(object source, ServerValidateEventArgs args)

    {

        Uri urlCheck = new Uri(txtWebsite.Text);

        WebRequest request = WebRequest.Create(urlCheck);

 

        WebResponse response;

        try

        {

            response = request.GetResponse();

            args.IsValid = true;

        }

        catch (WebException)

        {

            args.IsValid = false;

            return;

        }

    }

 

Using Client Side validation

To validate a Checkbox,

<asp:CheckBox ID="chkAgree" runat="server"

                        Text="I agree to the Terms and Conditions" />

                    <asp:CustomValidator ID="CustomValidator2" runat="server"

                       ClientValidationFunction="CheckAgree"

                       ErrorMessage="You have to agree the terms and condition to save this form."></asp:CustomValidator>

 

<script language="javascript">

        function CheckAgree(source, args) {

            var chk = document.getElementById('chkAgree')

            if (chk.checked) {

                args.IsValid = true;

            }

            else {

                args.IsValid = false;

            }

            return;

        }

    </script>

 

ValidationSummary control

This control actually does not do validation but can be used to group the validation messages of the validator controls on a page to display at a position. For example, top or bottom. To make this work, drag a ValidationSummary control into the page where we need to display the messages and make the display property of all the validator controls to none.

 

   <asp:ValidationSummary ID="ValidationSummary1" runat="server" />

 

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"

                        ControlToValidate="txtName" ErrorMessage="Name is mandatory." Display="None"></asp:RequiredFieldValidator>

 

<asp:TextBox ID="txtFatherName" runat="server"></asp:TextBox>

                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"

                        ControlToValidate="txtFatherName" ErrorMessage="Father's Name is mandatory." Display="None"></asp:RequiredFieldValidator>

 

ValidationGroup in ASP.Net 2.0

ValidationGroup is a new feature that is added with ASP.Net 2.0 to group the validator control. This feature enables developer to group the validator control with a particular server control that is generating a postback.

Read more about this feature in this article - Validation group in ASP.Net 2.0

 

Some Useful Tips

Ø       Page.IsValid

Since all the validator control depends on javascript for validation, it is not secure enough because there is a possibility that javascript is disabled in the client PC. To make our application more secure, check the Page.IsValid property at the serverside which will return true if the validator on the page is evaluated successfully.

Ø       Display property

The default value of this property is Static, which means it reserves a space in the page for the validator control to display message. Hence, there will be white space in place of the validator control with the default value. Setting it to Dynamic will remove the white space and space will be allocated only if the validation message is enabled.

Ø       CausesValidation property

By default, the validator control will fire for all the controls that raise postback to server. To prevent the validation for particular control set CausesValidation property to false. Default is true for all controls that generate postback.

Ø       Useful Articles

Read some of the useful articles on validation control here,

Handling Validations Effectively With Validation Controls in ASP.Net Projects

Restrict Asp.Net Validator controls to Fire on Page Submit

 

Downloads

Download Source 

Conclusion

Thus, we have learned how to use the validator controls and some useful tips to use the validation controls in ASP.Net efficiently. Please post your valuable comments about this article. Download the source attached with this article to see all the validator controls in action.

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments