Wednesday, February 27, 2008

Required Field Validator

In many webforms we come across scenarios where some fields should be made mandatory before they can submit the form. The required field validator was introduced into asp.net just for that purpose. Suppose we have a webform with 2 text boxes, name and email. What we would need now is to make the email field mandatory. That is if the user doesn't enter the email field and tries to submit the form, we need to give him a message saying that email is required. To do that add a required field validator (find it user the validation tab of visual studio) control and set its "Text" property to "Email Required" or any other error message that you want to post. Thats it. The complete code is given below.

<div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="txtEmail" runat="server"
ErrorMessage="RequiredFieldValidator" Text="EmailRequired" /><br />
Name:&nbsp;
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
Email: &nbsp;
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>

To make things interesting now..add another button saying something like "search" anywhere in the form. and try to run the application and press the search button instead..as you can see the form still does the validation check which was not intended to be done with the search button. There are 2 ways to get around this.
Either set the "CausesValidation" property of the search button to "false" or set the "ValidationGroup" property of both the validator and the submit button to the same name. The code with the second option is given below.

<div>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
ControlToValidate="txtEmail" ValidationGroup="myGroup" runat="server"
ErrorMessage="RequiredFieldValidator" Text="Email Required" /><br />
Name:&nbsp;
<asp:TextBox ID="txtName" runat="server"></asp:TextBox><br />
Email: &nbsp;
<asp:TextBox ID="txtEmail" runat="server"></asp:TextBox><br />
<br />
<asp:Button ID="Button1" ValidationGroup="myGroup"
runat="server" Text="Submit" />
<asp:Button ID="Button2" runat="server" Text="Search" />
</div>

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home