Tutorial on Required Field Validator in ASP.NET

HOME                AJAX                  VALIDATION                 EMAIL                 ADO.NET               SILVERLIGHT                 CONTACT US  




This tutorial is the first part of the ASP.NET Validation tutorial series. This tutorial will demonstrate how to use the required field validator for server side validation using ASP.NET 4.0. 

What is the RequiredFieldValidator?
The required field validator is an ASP.NET control that allows us to validate that a field has data before continuing. The required field validator uses server side validation to check a specified control for data. This validator is both extremely simple to use and powerful. An example of where you would use this would be for something like a user registration, in which you have a text box for the user to enter a username that is required to go on.


Using the RequiredFieldValidatorTo demonstrate this control, we will create a simple web site in which we will have a text box and button. The button will initiate validation on the text box and our required field validator will determine if an error needs to be displayed or if we can move on. To do this, create a new ASP.NET Empty Web Site and:
  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'Default.aspx'.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a textbox onto the web form.
  8. Drag and drop a requiredfieldvalidator onto the web form.
  9. In properties of  requiredfieldvalidator ,Change the ErrorMessage property to 'Text box is required!'.
  10. In properties of  requiredfieldvalidator , Change the ControlToValidate property to 'TextBox1'.
  11. In properties of  requiredfieldvalidator , "Set focus on error" to true
  12. Drag and drop a button onto the web form.
What this has done, is associated the text box we added with the required field validator. In this case, it should display an error message if the text box is empty and the button is clicked.


TestingTo test this out, simply load up the web site and click the button. Notice that the error message we specified earlier is displayed. The text box did not pass validation because it is required to contain some sort of data. Go ahead and add some text to the text box and then click the button, notice the error message was not displayed meaning it passed validation.












HOME                 AJAX                   VALIDATION                  EMAIL                  ADO.NET                  SILVERLIGHT                  CONTACT US

No comments:

Post a Comment