Professional Documents
Culture Documents
Form Validation
Form Validation
In this example, we have a textbox which will not be valid until the user
types something in. Inside the validator tag, we have a single *. The text in
the innerhtml will be shown in the controltovalidate if the control is not
valid. It should be noted that the ErrorMessage attribute is not what is
shown. The ErrorMessage tag is shown in the Validation Summary (see below).
Here we have an example where the two textboxes must be equal. The tags that are
unique to this control is the ControlToCompare attribute which is the
control that will be compared. The two controls are compared with the type of
comparison specified in the Operator attribute. The Operator
attribute can contain Equal, GreterThan, LessThanOrEqual, etc. Another usage of
the ComapareValidator is to have a control compare to a value. For example:
Field: <asp:textbox id="textbox1" runat="server"/>
<asp:CompareValidator id="valRequired" runat="server"
ControlToValidate="textbox1"
ValueToCompare="50"
Type="Integer"
Operator="GreaterThan"
ErrorMessage="* You must enter a number greater than 50"
Display="dynamic">*
</asp:CompareValidator>
The data type can be one of: Currency, Double, Date, Integer or String, string
being the default data type.
ValidationExpression=".*@.*\\..*"
ErrorMessage="* Your entry is not a valid e-mail address."
display="dynamic">*
</asp:RegularExpressionValidator>
is the function that is server-side to check for validation if client does not
support client-side validation.
Client Validation function:
<script language="Javascript">
<!-/* ... Code goes here ... */
//-->
</script>
Validation Summary
ASP.NET has provided an additional control that complements the validator
controls. This is the validation summary control which is used like:
The validation summary control will collect all the error messages of all the
non-valid controls and put them in a tidy list. The list can be either shown on
the web page (as shown in the example above) or with a popup box (by specifying
ShowMessageBox="True")
Now you know how to use the Validator Controls in ASP.NET! Have fun!
Acknoledgment: Professional ASP.NET (published by Wrox) was
used a reference. It's a good book!
Tips to remember
If you are doing server-side validation, make sure the button onclick
method has a Page.IsValid if statement or it will look like your validators
aren't doing anything
Don't forget to wrap everything in the <form runat=server> tag.