ASP.NET | Validations
Now since we have already learned how to add a new Web Form or .aspx file in our web site, the next thing to learn is how to add validations in our textboxes and other objects. To do that, read the instructions and example below:
1. Our objective is to add a registration-like form in our web application, so first we add the objects we would like to, like textboxes, labels, etc. First, add a label by dragging and dropping a Label object from the Toolbox (right side in VS2010) to your form, in CSWD01_Tutorial.aspx (design mode) right below the header that says “CSWD01 ASP.NET TUTORIAL”. Once the Label object is in our form, rename it from “Label” to “First Name:”. You can edit the formatting of the text, like font, size and color, but in this tutorial we will just stick with the default formatting supplied by VS.
2. After that, drag and drop a TextBox from the toolbox to the form, 3 spaces right next to the Label we just added.
We want users to input data in our textbox before clicking the “Submit” button, meaning, users can’t go on to the next form without their first name left empty. To do that, we will add validations in our objects. In our “First Name” textbox field, we will use the RequiredFieldValidator which can be drag and dropped from the toolbox, under the Validation category.
Now rename the ErrorMessage property value from “RequiredFieldValidator” to “*Required Field”.
Again, in the properties of our RequiredFieldValidator, change the value of ControlToValidate to “TextBox1”, so that our validator will take effect once the value of TextBox1 is empty.
Right after that, we would like to test if our validator works properly. To do that, drag and drop a Button from the Toolbox to our form, below the textbox and the validator.
Now change the textproperty of the button to “SUBMIT”.
Also, to make sure that once we click the button, the validation will take effect just before showing up the next form, we will modify the PostBackUrl property of the Button to another .aspx file in our web app. In this tutorial, we will just use “Default.aspx”, so that when we clicked the button and the validation passes, the Default.aspx will show up.
Now try running the Web app and test if the validation works. If you leave your textbox with an empty value and clicked the button, the validation will show up right next to the textbox and the next page will not show up.
But if you entered a value and clicked the button, the Default.aspx will show up.
You can start self-studying other forms of validations like RangeValidator, CompareValidator, etc.
Now, CSWD01 P1, for your Finals MP1, modify the page and make it look like this:
You are free to add some more content and validations as long as the following are there.
|> At The Drive-in – One Armed Scissor