Contents

Tuesday, 3 January 2017


 RequiredFieldValidator Control

RequiredFieldValidator Control is used in an ASP.NET application to validate a particular field is empty or not. For example, you have seen in a registration form user have some of the compulsory field which need to be filled like their name,password,address etc. These field cannot be left empty and if left empty the page generates an error. So in order to generate these kinds of error we can use the validation control named RequiredFieldValidator. It will check for an empty field and if found then it prints an error.

So lets take an example to understand it well. I am going to take the same example of a registration form were we take input for name, blog name and nickname of a particular user. I will set RequiredFieldValidator for name and blog name textboxes and not for nickname as i am assuming that our project is not concerned with nicknames of a user. So after adding these textboxes to our project we also need to add RequiredFieldValidator control for each textboxes that requires validation. All the validation controls can be added just by dragging and dropping these controls for the toolbox under validation.

After adding the required control we also need to change few properties for these. Properties can be set either through the properties window usually found in the right side for the screen or just manually typing the required property to the validation control through the source code. 

After dragging and dropping we will get it as following:

Source View


<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator>

After adding few properties for validation:

<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
            ErrorMessage="Name cannot be empty !!" ForeColor="Red" ControlToValidate="TextBox1" ></asp:RequiredFieldValidator>

Properties


ID - ID of the control

runat - As we need to run it on the server

ErrorMessage - It specifies the error which need to be printed when a particular textbox is empty.

ForeColor - This property is added to change the color of the error message.

ControlToValidate - It is added to specify which web control we need to validate(i.e it specifies the ID of the control which needs to be validated. In the above code we are validating TextBox1)

Design View

Output


In the above output you may see that i have not entered the Blog Name so it generated an Error stating that it cannot be blank. Nickname field is not generating an error as we have not set the validation for that texbox.

The best part of these validation controls are it does not allow us to redirect a page to another unless all the validations are satisfied. This is done automatically.


You may click the Content tab to see all the posts that i will cover in this tutorial for easy navigation.
 

 

No comments:

Post a Comment