Controls for Validating User Input


A large percentage of the code in a typical application is devoted to validating the input received from the user. ASP.NET dedicates five server controls to making this step more manageable: RequiredFieldValidator, CompareValidator, RangeValidator, RegularExpressionValidator, and CustomValidator. These validation controls all inherit from the abstract BaseValidator class, which is derived from the Label class. An additional control can be used in conjunction with the validators, ValidationSummary, to present the set of errors in a cohesive and consistent manner.

Each of these validation controls has a ControlToValidate property used to set the ID of the target control. When the form is posted, the Validate method is called automatically; when validation fails, the ErrorMessage text is displayed. For some browsers, the validation controls are able to take advantage of client- side script to perform the validation check and display an error message without completing the postback.

Tip

If necessary, you can disable client-side validation by using the Page directive’s ClientTarget attribute. Setting this directive to downlevel causes ASP.NET to treat the browser as though it does not support JScript.

The Display property is used to indicate whether space should be reserved in the rendering for the error message. It can be set to one of the two ValidatorDisplay enumeration values: Static or Dynamic. The Static setting, where space is allocated but not immediately filled, works only when the client supports client-side scripting and the Page directive’s ClientTarget attribute has not been set to downlevel.

RequiredFieldValidator

The RequiredFieldValidator control enforces data entry on the part of the user. No constraints are placed on the value of the data provided, but some type of data must be entered. Code Listing 2-14 demonstrates using the RequiredFieldValidator control to ensure that data has been entered for an e-mail address.

Code Listing 2-14: EmailRequired.aspx

start example
 <form runat="server">
Please enter your email address
<asp:RequiredFieldValidator runat="server"
ControlToValidate="emailTextbox"
ErrorMessage="email required" Display="Static" />
<asp:Textbox runat="server" />
<asp:button type="submit" runat="server" Text="Submit" />
</form>
end example

Note

When used with sophisticated clients, client-side validation can reduce server load and improve the customer experience by providing immediate feedback about a problem without issuing a request to the server.

CompareValidator

The CompareValidator control can check against static or dynamic values. In addition, it can compare the value with the value of another control. To compare with a value, use the ValueToCompare property. Switch to the ControlToCompare property to use the value of another control from the page. The use of these properties is mutually exclusive. Code Listing 2-15 demonstrates using the CompareValidator control to check that the provided string, when converted to an integer, is greater than or equal to 18.

Code Listing 2-15: CompareValidator.aspx

start example
 <form runat="server">
Enter your age:
<asp:CompareValidator runat="server" Type="integer"
ValueToCompare="18" ControlToValidate="ageTextBox"
ErrorMessage="Must be 18 to vote."
Operator="GreaterThanEqual"/>
<asp:TextBox runat = "server" />
<asp:Button type="submit" runat="server" Text="Submit" />
</form>
end example

The operator property can be set to any of the values from the ValidationCompareOperator enumeration: Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck. The DataTypeCheck operator is an interesting operator that can be applied in unique ways. Normally, the value of the control being validated is converted to the type specified by the Type property, and an exception is thrown if the conversion fails. The DataTypeCheck operator provides a means of explicitly checking that the type entered can be converted, but it does not cause an exception to be thrown for illegal conversions. The ValueToCompare and ControlToCompare properties are not used, even when specified, when the validator’s operator property is set to DataTypeCheck. (Note that if the operator property is not specified, the default is to check for value equality.)

RangeValidator

The RangeValidator control has properties for specifying minimum and maximum values. The value being confirmed must fall between those values inclusive of the range limits. In Code Listing 2-16 we add a programmatic check against the validator. Once the data is found to be valid against the coded constraints, the instructions are changed to provide more appropriate information.

Code Listing 2-16: RangeValidator.aspx

start example
 <script runat="server" language="C#" >
protected void Page_Load(object o, EventArgs e) {
if(IsPostBack && rangeValidator.IsValid ){
message.Text = "Thanks, see you in September.";
}
else {
message.Text = "Please start vacations on 2003/08/01";
}
}
</script>
<form runat="server">
Enter your desired vacation start date:
<asp:Textbox runat="server" />
<asp:RangeValidator runat="server"
ControlToValidate="theDate"
ErrorMessage="vacations must start on August 1st"
Type="Date" MinimumValue="2003/08/01"
MaximumValue="2003/08/01"/><br />
<b><asp:label runat="server" /></b><br />
<asp:button type="submit" runat="server" Text="Submit" />
</form>
end example

RegularExpressionValidator

The ability to use regular expressions in validators opens up great possibilities for powerful input checking without writing lots of code. The RegularExpressionValidator control accepts a string in the ValidationExpression property that is applied to the input contained in the control specified by the ControlToValidate property. A new regular expression is created using ValidationExpression, and the value is tested for conformity. If you’ve written code to verify that an e- mail address does indeed appear to be an e-mail address without using regular expressions, you’ll appreciate the sample address validation in Code Listing 2- 17. Notice that an empty string will pass the regular expression in the sample. Use a RegularExpressionValidator in conjunction with a RequiredFieldValidator to ensure input. In many circumstances, the combination of several validators is simpler than producing a single regular expression that accounts for all the desired validity checks.

Code Listing 2-17: RegularExpressionValidator.aspx

start example
 <form runat="server">
Enter your email address, which will be sold to third parties:
<asp:textbox runat="server" /><br />
<asp:RegularExpressionValidator runat="server"
ValidationExpression
="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
ControlToValidate="emailAddress"
ErrorMessage="At least make it look like a real address."/>
<br />

<asp:button type="submit" runat="server" Text="Submit" />
</form>
end example

CustomValidator

The CustomValidator control differs from the other validators in that it lets you provide custom client-side and server-side validation code. The ClientValidationFunction property can be set to a script block string that will be passed through to the browser for execution when the form is being submitted. If the custom code sets the argument object’s IsValid property to false, the form will not be submitted.

The value of the control specified in the ControlToValidate property is passed to the custom validation code as the Value property of the ServerValidateEventArgs parameter. In Code Listing 2-18, we provide an event handler for the OnServerValidate event that demonstrates accessing the value and setting the IsValid property of the same object to indicate whether the user’s input has passed scrutiny. In this example, the user can’t succeed because we always set IsValid to false and customize the ErrorMessage to encourage the user to modify her input no matter what she enters.

Code Listing 2-18: CustomValidator.aspx

start example
 <script runat="server" language="C#">
protected void ServerAddMoreValidation(object o,
ServerValidateEventArgs e) {
try {
//whatever they enter, it is insufficient by one
int theInput = Int32.Parse(e.Value);
if (theInput < 0) {
theValidator.ErrorMessage
= "please enter a positive value";
}
else {
theValidator.ErrorMessage = "please enter at least "
+ (theInput + 1).ToString();
}
}
catch {
}
e.IsValid = false;
}
</script>
<form runat="server">
Enter the quantity:
<asp:textbox runat="server" />
<asp:CustomValidator runat="server"
ControlToValidate="quantity"
OnServerValidate="ServerAddMoreValidation"
ErrorMessage="Try Again"/><br />
<asp:label runat="server" /><br />
<asp:button type="submit" runat="server" Text="Submit" />
</form>
end example

Be aware that the client script provided for the CustomValidator control should act only as the first line of defense in the validation work. A malicious user can get around the script code and post bogus data directly to the server.

Tip

Always verify the data received by the server, even when client- side validation code has been provided. You can’t safely assume anything—the client might not have run the code, and the user might have constructed a malicious request by hand with values that would not pass the examination of the client-side code.

ValidationSummary

As you’ve learned, when verifying user input, the validation controls can save you lines and lines of custom code. In many cases, you will add several validators to the page for a field requiring a single input: a RequiredField validator control to enforce the submission of data as well as a RangeValidator or CustomValidator control to more closely scrutinize the data. The proliferation of error messages on a page can be somewhat daunting for the user, particularly if the Display property is dynamic, which causes the HTML elements to potentially shift slightly based on the presence of error messages. The ValidationSummary control coalesces the page’s error messages into a central location. The control’s HeaderText is displayed at the top of the error message list, which is generated from the controls failing validation.




Microsoft ASP. NET Coding Strategies with the Microsoft ASP. NET Team
Microsoft ASP.NET Coding Strategies with the Microsoft ASP.NET Team (Pro-Developer)
ISBN: 073561900X
EAN: 2147483647
Year: 2005
Pages: 144

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net