Subscribe

RSS Feed (xml)

Validating User Form Input in ASP.NET

ASP.NET ships with a suite of validation controls that make form validation a relatively
simple process for most rules.These include the following controls:
n RequiredFieldValidator
n RangeValidator
n CompareValidatior
n RegularExpressionValidator
n CustomValidator
In addition, display of error messages is eased by the use of the ValidationSummary
control.The following code sample demonstrates each of these validators and includes
comments describing their various properties where it may not be immediately obvious.
<%@ Page language=”vb” %>
<%@ Import namespace=”System.Web.UI.WebControls” %>
<script runat=”server”>
Public Sub button1_Click(sender As Object, e As System.EventArgs)
Label1.Text = “Hello, the time is now “ & DateTime.Now.ToLongTimeString() & _
“<br>Page.IsValid = “ & Page.IsValid
End Sub
Public Sub ServerValidate(sender As Object, args As ServerValidateEventArgs)
Dim num As Integer = Int32.Parse(args.Value)
If num Mod 2 = 0 Then
args.IsValid = True
Else
args.IsValid = False
End If
End Sub
</script>
<script type=”text/javascript”>
function isEven(oSrc, args){
//var _sqrt = Math.round(Math.sqrt(args.Value));
args.IsValid = (args.Value % 2 == 0);
}
</script>
<html>
<body>
<form method=”post” runat=”server”>
<table>
<tr>
<td>
RequiredFieldValidator
</td>
<td>
<asp:textbox id=”TextBox1” runat=”server” />
</td>
<td width=”400”>
<!—
These RequiredFieldValidator properties are common to all validators.
ControlToValidate links the validator to another Web control and is
required for all validators.
Text is displayed where the validator is located when there is a
ValidationSummary.
ErrorMessage is displayed in the ValidationSummary.
Display can be Static or Dynamic.
When it is static, the browser will hold
space for the validator’s output.
When it’s Dynamic, the browser will resize as
needed when the validator is triggered.
In addition, you can specify a value for InitialValue, which is useful
if you have a form element with some default text in it, such as
“Enter a value”. Note that if a non-blank value is specified for
InitialValue,
a blank value will then be considered valid.
—>
<asp:RequiredFieldValidator id=”TextBox1Required”
runat=”server” ControlToValidate=”TextBox1”
Text=”*” Display=”Static”
ErrorMessage=”RequiredFieldValidator field is required.” />
</td>

</tr>
<tr>
<td>
RangeValidator
</td>
<td>
<asp:textbox id=”TextBox2” runat=”server” />
<br>
</td>
<td>
<!—
The RangeValidator supports properties
MinimumValue and MaximumValue, which are self-explanatory, and
Type, which must be one of Currency, Date, Double, Integer, or String.
—>
<asp:RangeValidator id=”TextBox2Range”
ControlToValidate=”TextBox2” MinimumValue=”2”
MaximumValue=”5” Type=”Integer” Text=”Invalid!”
runat=”server” Display=”Dynamic”
ErrorMessage=”RangeValidator value must be between 2 and 5 inclusive.” />
</td>
</tr>
<tr>
<td>
CompareValidator: Integer Field
</td>
<td>
<asp:textbox id=”TextBox3” runat=”server” />
</td>
<td>
<!—
The CompareValidator adds the following properties:
Operator - can be a comparison operator, such as Equal, GreaterThan,
GreaterThanEqual, LessThan, LessThanEqual, NotEqual
or can be DataTypeCheck as it is here.
DataTypeCheck will simply validate that the value of the
ControlToValidate is of the specified type.
Not shown is the ValueToCompare, which can be used to specify
a particular value to which the ControlToValidate should be compared.
Not used for DataTypeCheck.
—>
<asp:CompareValidator id=”TextBox3CompareInteger”
ControlToValidate=”TextBox3” Operator=”DataTypeCheck”
Type=”Integer” Text=”!” Display=”Dynamic”
ErrorMessage=”CompareValidator - Value must be an integer.”
runat=”server” />

</td>
</tr>
<tr>
<td>
CompareValidator: One Integer field less than other
</td>
<td>
<asp:textbox id=”TextBox4” runat=”server” />
<br>
<asp:textbox id=”TextBox5” runat=”server” />
</td>
<td>
<!—
The CompareValidator can be used to compare the values of two controls by
specifying a control in the ControlToCompare property. Note that
ControlToCompare
and ValueToCompare cannot both be set for a particular control.
—>
<asp:CompareValidator id=”TextBox45Compare”
ControlToValidate=”TextBox4” ControlToCompare=”TextBox5”
Operator=”LessThan” Type=”Integer” Text=”A must be < B”
runat=”server” Display=”Dynamic”
ErrorMessage=”CompareValidator: First field must be less than second field.” />
</td>
</tr>
<tr>
<td>
RegularExpressionValidator
</td>
<td>
<asp:textbox id=”TextBox6” runat=”server” />
<br>
</td>
<td>
<!—
ValidationExpression refers to a valid regular expression.
The beginning of string (^)
and end of string characters ($) are optional for these expressions
and are always assumed by
the control. You’ll find many sample regular expressions at
http://regexlib.com/.
Note that the Text property can also be set by placing a value between
the opening and closing
tags of a validator, as shown below.
—>

<asp:RegularExpressionValidator id=”TextBox6Regex”
runat=”server” ControlToValidate=”TextBox6”
ValidationExpression=”^\d{5}$” Display=”Dynamic”
ErrorMessage=”RegularExpression:Zip code must be 5 numeric digits”>
*</asp:RegularExpressionValidator>
</td>
</tr>
<tr>
<td>
CustomValidator: Even Number
</td>
<td>
<asp:textbox id=”TextBox7” text=”3” runat=”server” />
<br>
</td>
<td>
<!—
The CustomValidator supports one property and one event. The property
is ClientValidationFunction and the event is ServerValidate. You
can specify a client-side function with the former property which will
be used for client-side validation, and you can handle the
ServerValidate event for server-side validation. The client and server
functions must follow the design shown in the <script> blocks at
the top of this listing.
—>
<asp:CustomValidator id=”TextBox7Custom” runat=”server”
ControlToValidate=”TextBox7”
OnServerValidate=”ServerValidate” Display=”Dynamic”
ErrorMessage=”Must be an even number!”
ClientValidationFunction=”isEven”>
*</asp:CustomValidator>
</td>
</tr>
</table>
<p>
<asp:Button id=”Button1” onClick=”Button1_Click”
text=”Save” runat=”server” />
<p>
<asp:Label id=”Label1” runat=”server” />
<p>
<!—
The ValidationSummary control supports properties that control how it is
displayed, such as HeaderText, which controls the header.
DisplayMode must be one of BulletList, List, or SingleParagraph.
ShowMessageBox, when true, will display a JavaScript Alert with the
contents of the validation summary.

ShowSummary, when false, will hide the summary on the page.
This can be useful if no
errors are to be output to the browser but the summary is to be logged,
for instance.
—>
<asp:ValidationSummary ID=”ValidationSummary1” runat=”server”
HeaderText=”Error in the following field(s):”
DisplayMode=”BulletList” />
</form>
</body>
</html>

Remember that all validators run both client-side and server-side, and that you should
always check Page.IsValid to ensure that its value is True before you perform any
operations on the data that was submitted.

No comments:

Variety in the Web World