Validating User Input in ASP.NET Web Pages (Razor) Sites
This article discusses how to validate information you get from users — that is, to make sure that users enter valid information in HTML forms in an ASP.NET Web Pages (Razor) site.
What you'll learn:
- How to check that a user's input matches validation criteria that you define.
- How to determine whether all validation tests have passed.
- How to display validation errors (and how to format them).
- How to validate data that doesn't come directly from users.
These are the ASP.NET programming concepts introduced in the article:
- The
Validationhelper (for ASP.NET Web Pages 2). - The
ModelStateclass (for ASP.NET Web Pages 1.0). - The
Html.ValidationSummaryandHtml.ValidationMessagemethods.
Note The information in this article applies to ASP.NET Web Pages 1.0 and ASP.NET Web Pages 2. Where there are differences between versions, the text describes the differences.
This article contains the following sections:
- Overview of User Input Validation
- Validating User Input in ASP.NET Web Pages 2
- Adding Client-Side Validation (in ASP.NET Web Pages 2)
- Formatting Validation Errors
- Validating Data That Doesn't Come Directly from Users
- Validating User Input in ASP.NET Web Pages 1.0
Overview of User Input Validation
If you ask users to enter information in a page — for example, into a form — it's important to make sure that the values that they enter are valid. For example, you don't want to process a form that's missing critical information.
When users enter values into an HTML form, the values that they enter are strings. In many cases, the values you need are some other data types, like integers or dates. Therefore, you also have to make sure that the values that users enter can be correctly converted to the appropriate data types.
You might also have certain restrictions on the values. Even if users correctly enter an integer, for example, you might need to make sure that the value falls within a certain range.

Important Validating user input is also important for security. When you restrict the values that users can enter in forms, you reduce the chance that someone can enter a value that can compromise the security of your site.
Differences in Validation Between ASP.NET Web Pages 1.0 and ASP.NET Web Pages 2
ASP.NET Web Pages 2 introduced some features that make it easier to perform validation testing. The primary differences are the following:
The
Validationhelper has methods that can automatically perform validation tests. It can check for a required field, check for a data type like integer or date, check for a range or string length, and so on.The
Validationhelper includes support for automatically performing validation checks in client script.
You can perform validation in ASP.NET Web Pages 1.0 fairly easily; it's just that you
must define the validation checks more explicitly in code. You can still take advantage of
features like the Html.ValidationSummary method to display validation errors. For more information,
see Validating
User Input in ASP.NET Web Pages 1.0 later in this article.
Validating User Input in ASP.NET Web Pages 2
In ASP.NET Web Pages 2, you can use the Validator helper to test user input.
The basic approach is to do the following:
Determine which input elements (fields) you want to validate.
You typically validate values in
<input>elements in a form. However, it's a good practice to validate all input, even input that comes from a constrained element like a<select>list. This helps to make sure that users don't bypass the controls on a page and submit a form.In the page code, add individual validation checks for each input element by using methods of the
Validationhelper.To check for required fields, use
Validation.RequireField(field, [error message])(for an individual field) orValidation.RequireFields(field1, field2, ...))(for a list of fields). For other types of validation, useValidation.Add(field, ValidationType). ForValidationType, you can use these options:Validator.DateTime ([error message])
Validator.Decimal([error message])
Validator.EqualsTo(otherField [, error message])
Validator.Float([error message])
Validator.Integer([error message])
Validator.Range(min, max [, error message])
Validator.RegEx(pattern [, error message])
Validator.Required([error message])
Validator.StringLength(length)
Validator.Url([error message])When the page is submitted, check whether validation has passed by checking
Validation.IsValid:if(IsPost && Validation.IsValid()){ // Process form submit }If there are any validation errors, you skip normal page processing. For example, if the purpose of the page is to update a database, you don't do that until all validation errors have been fixed.
If there are validation errors, display error messages in the page's markup by using
Html.ValidationSummaryorHtml.ValidationMessage, or both.
The following example shows a page that illustrates these steps.
@{
var message="";
// Specify validation requirements for different fields.
Validation.RequireField("coursename", "Class name is required");
Validation.RequireField("credits", "Credits is required");
Validation.Add("coursename", Validator.StringLength(5));
Validation.Add("credits", Validator.Integer("Credits must be an integer"));
Validation.Add("credits", Validator.Range(1, 5, "Credits must be between 1 and 5"));
Validation.Add("startDate", Validator.DateTime("Start date must be a date"));
if (IsPost) {
// Before processing anything, make sure that all user input is valid.
if (Validation.IsValid()) {
var coursename = Request["coursename"];
var credits = Request["credits"].AsInt();
var startDate = Request["startDate"].AsDateTime();
message += @"For Class, you entered " + coursename;
message += @"<br/>For Credits, you entered " + credits.ToString();
message += @"<br/>For Start Date, you entered " + startDate.ToString("dd-MMM-yyyy");
// Further processing here
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Validation Example</title>
<style>
body {margin: 1in; font-family: 'Segoe UI'; font-size: 11pt; }
</style>
</head>
<body>
<h1>Validation Example</h1>
<p>This example page asks the user to enter information about some classes at school.</p>
<form method="post">
@Html.ValidationSummary()
<div>
<label for="coursename">Course name: </label>
<input type="text"
name="coursename"
value="@Request["coursename"]"
/>
@Html.ValidationMessage("coursename")
</div>
<div>
<label for="credits">Credits: </label>
<input type="text"
name="credits"
value="@Request["credits"]"
/>
@Html.ValidationMessage("credits")
</div>
<div>
<label for="startDate">Start date: </label>
<input type="text"
name="startDate"
value="@Request["startDate"]"
/>
@Html.ValidationMessage("startDate")
</div>
<div>
<input type="submit" value="Submit" class="submit" />
</div>
<div>
@if(IsPost){
<p>@Html.Raw(message)</p>
}
</div>
</form>
</body>
</html>
To see how validation works, run this page and deliberately make mistakes. For example, here's what the page looks like if you forget to enter a course name, if you enter an , and if you enter an invalid date:
Adding Client-Side Validation (in ASP.NET Web Pages 2)
By default, user input is validated after users submit the page — that is, the validation is performed in server code. A disadvantage of this approach is that users don't know that they've made an error until after they submit the page. If a form is long or complex, reporting errors only after the page is submitted can be inconvenient to the user.
In ASP.NET Web Pages 2, you can add support to perform validation in client script. In that case, the validation is performed as users work in the browser. For example, suppose you specify that a value should be an integer. If a user enters a non-integer value, the error is reported as soon as the user leaves the entry field. Users get immediate feedback, which is convenient for them. Client-based validation can also reduce the number of times that the user has to submit the form to correct multiple errors.
Note Even if you use client-side validation, validation is always also performed in server code. Performing validation in server code is a security measure, in case users bypass client-based validation.
- Register the following JavaScript libraries in the page:
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js"> </script> <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.js"> </script> <script src="~/Scripts/jquery.validate.unobtrusive.js"> </script>
Two of the libraries are loadable from a content delivery network (CDN), so you don't necessarily have to have them on your computer or server. However, you must have a local copy of jquery.validate.unobtrusive.js. If you are not already working with a WebMatrix template (like Starter Site) that includes the library, create a Web Pages site that's based on Starter Site. Then copy the .js file to your current site. - In markup, for each element that you're validating, add a call to
Validation.For(field). This method emits attributes that are used by client-side validation. (Rather than emitting actual JavaScript code, the method emits attributes likedata-val-.... These attributes support unobtrusive client validation that uses jQuery to do the work.)
The following page shows how to add client validation features to the example shown earlier.
@{
// Note that client validation as implemented here will work only with
// ASP.NET Web Pages 2.
var message="";
// Specify validation requirements for different fields.
Validation.RequireField("coursename", "Class name is required");
Validation.RequireField("credits", "Credits is required");
Validation.Add("coursename", Validator.StringLength(5));
Validation.Add("credits", Validator.Integer("Credits must be an integer"));
Validation.Add("credits", Validator.Range(1, 5, "Credits must be between 1 and 5"));
Validation.Add("startDate", Validator.DateTime("Start date must be a date"));
if (IsPost) {
// Before processing anything, make sure that all user input is valid.
if (Validation.IsValid()) {
var coursename = Request["coursename"];
var credits = Request["credits"].AsInt();
var startDate = Request["startDate"].AsDateTime();
message += @"For Class, you entered " + coursename;
message += @"<br/>For Credits, you entered " + credits.ToString();
message += @"<br/>For Start Date, you entered " + startDate.ToString("dd-MMM-yyyy");
// Further processing here
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Validation Example with Client Validation</title>
<style>
body {margin: 1in; font-family: 'Segoe UI'; font-size: 11pt; }
</style>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js"></script>
<script
src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.js">
</script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
</head>
<body>
<h1>Validation Example with Client Validation</h1>
<p>This example page asks the user to enter information about some classes at school.</p>
<form method="post">
@Html.ValidationSummary()
<div>
<label for="coursename">Course name: </label>
<input type="text"
name="coursename"
value="@Request["coursename"]"
@Validation.For("coursename")
/>
@Html.ValidationMessage("coursename")
</div>
<div>
<label for="credits">Credits: </label>
<input type="text"
name="credits"
value="@Request["credits"]"
@Validation.For("credits")
/>
@Html.ValidationMessage("credits")
</div>
<div>
<label for="startDate">Start date: </label>
<input type="text"
name="startDate"
value="@Request["startDate"]"
@Validation.For("startDate")
/>
@Html.ValidationMessage("startDate")
</div>
<div>
<input type="submit" value="Submit" class="submit" />
</div>
<div>
@if(IsPost){
<p>@Html.Raw(message)</p>
}
</div>
</form>
</body>
</html>
Not all validation checks run on the client. In particular, data-type validation (integer, date, and so on) don't run on the client. The following checks work on both the client and server:
RequiredRange(minValue, maxValue)StringLength(maxLength[, minLength])Regex(pattern)EqualsTo(otherField)
In this example, the test for a valid date won't work in client code. However, the test will be performed in server code.
Formatting Validation Errors
You can control how validation errors are displayed by defining CSS classes that have the following reserved names:
field-validation-error. Defines the output of theHtml.ValidationMessagemethod when it's displaying an error.field-validation-valid. Defines the output of theHtml.ValidationMessagemethod when there is no error.input-validation-error. Defines how<input>elements are rendered when there's an error. (For example, you can use this class to set the background color of an <input> element to a different color if its value is invalid.) This CSS class is used only during client validation (in ASP.NET Web Pages 2).input-validation-valid. Defines the appearance of<input>elements when there is no error.validation-summary-errors. Defines the output of theHtml.ValidationSummarymethod it's displaying a list of errors.validation-summary-valid. Defines the output of theHtml.ValidationSummarymethod when there is no error.
The following <style> block shows rules for error conditions.
<style>
.validation-summary-errors {
border:2px solid red;
color:red;
font-weight:bold;
margin:6px;
width:30%;
}
.field-validation-error{
color:red;
font-weight:bold;
background-color:yellow;
}
.input-validation-error{
color:red;
font-weight:bold;
background-color:pink;
}
</style>
If you include this style block in the example pages from earlier in the article, the error display will look like the following illustration:

Note If you're not using client validation in ASP.NET Web
Pages 2, the CSS classes for the <input> elements (input-validation-error
and input-validation-valid don't have any effect.
Static and Dynamic Error Display
The CSS rules come in pairs, such as validation-summary-errors
and validation-summary-valid. These pairs let you define rules for both
conditions: an error condition and a "normal" (non-error) condition. It's
important to understand that the markup for the error display is always rendered,
even if there are no errors. For example, if a page has an
Html.ValidationSummary method in the markup, the page source will contain
the following markup even when the page is requested for the first time:
<div class="validation-summary-valid"
data-valmsg-summary="true"><ul></ul></div>
In other words, the
Html.ValidationSummary method always renders a <div> element
and a list, even if the error list is empty. Similarly, the
Html.ValidationMessage method always renders a <span>
element as a placeholder for an individual field error, even if there is no
error.
In some situations, displaying an error message can cause the page to reflow
and can cause elements on the page to move around. The CSS rules that end in -valid let you define
a layout that can help prevent this problem. For example,
you can define field-validation-error and field-validation-valid
to both have the same fixed size. That way, the display area for the field is
static and won't change the page flow if an error message is displayed.
Validating Data That Doesn't Come Directly from Users
Sometimes you have to validate information that doesn't come directly from an HTML form. A typical example is a page where a value is passed in a query string, as in the following example:
http://server/myapp/EditClassInformation?classid=1022
In this case, you want to make sure that the value that's passed to the page
(here, 1022 for the value of classid) is valid. You can't directly
use the Validation helper to perform this validation. However, you can use other
features of the validation system, like the ability to display validation error
messages.
Important Always validate values that you get from any source, including form-field values, query-string values, and cookie values. It's easy for people to change these values (perhaps for malicious purposes). So you must check these values in order to protect your application.
The following example shows how you might validate a value that's passed in a query string. The code tests that the value is not empty and that it's an integer.
if(!IsPost){
if(!Request.QueryString["classid"].IsEmpty() && Request.QueryString["classid"].IsInt()) {
// Process the value
}
else{
Validation.AddFormError("No class was selected.");
}
}
Notice that the test is performed when the request is not a form submission (if(!IsPost)).
This test would pass the first time that the page is requested, but not when the
request is a form submission.
To display this error, you can add the error to the list of validation errors
by calling Validation.AddFormError("message"). If the page contains a call
to the Html.ValidationSummary method, the error is displayed there,
just like a user-input validation error.
Note In the Beta version of ASP.NET Web Pages 2
(before the RC version was released), the
Validation.AddFormError method did not exist. Instead, you could use the ModelState.AddFormError
method.
Validating User Input in ASP.NET Web Pages 1.0
ASP.NET Web Pages version 1.0 does not include the Validation
helper. However, you can use code to check user values and then use the
ModelState class to manage errors. You typically use the following
methods to test for errors and to display error messages:
- Use the
IsEmptymethod to make sure that users haven't forgotten to enter a value. - Use methods like
AsIntandAsDateTime(orIsIntandIsDateTime) to make sure that users have entered values that match certain data types. - Use other logic to check whether values are in a certain range, have a minimum length, and so on.
- Use
ModelState.AddErrorto "register" a validation error. - Use
ModelState.IsValidto determine whether any validation errors were registered. -
Use
Html.ValidationSummaryto display errors.
The following example shows how to combine these techniques to validate user input.
@{
var message = "";
var coursename = "";
int credits;
DateTime startDate;
if (IsPost) {
coursename = Request["coursename"];
if (coursename.IsEmpty() || coursename.Length > 5) {
ModelState.AddError("coursename", "Class name is required and cannot be longer than 5 characters.");
}
credits = Request["credits"].AsInt(-1);
// If the value is not an integer, -1 is returned.
if(credits < 1 || credits > 5) {
ModelState.AddError("credits", "Credits must be an integer between 1 and 5.");
}
startDate = Request["startDate"].AsDateTime();
if(startDate == DateTime.MinValue){
ModelState.AddError("startDate", "Start date is not valid.");
}
if(IsPost && ModelState.IsValid){
message += @"For Class, you entered " + coursename;
message += @"<br/>For Credits, you entered " + credits.ToString();
message += @"<br/>For Start Date, you entered " + startDate.ToString("dd-MMM-yyyy");
}
}
}
<!DOCTYPE html>
<html>
<head>
<title>Add Products</title>
<style type="text/css">
label {float:left; width: 8em; text-align: right;
margin-right: 0.5em;}
fieldset {padding: 1em; border: 1px solid; width: 35em;}
legend {padding: 2px 4px; border: 1px solid; font-weight:bold;}
.validation-summary-errors {font-weight:bold; color:red; font-size: 11pt;}
</style>
</head>
<body>
<h1>Class Information</h1>
<form method="post">
@Html.ValidationSummary()
<div>
<label for="coursename">Course: </label>
<input type="text"
name="coursename"
value="@Request["coursename"]"
/>
@Html.ValidationMessage("coursename")
</div>
<div>
<label for="credits">Credits: </label>
<input type="text"
name="credits"
value="@Request["credits"]"
/>
@Html.ValidationMessage("credits")
</div>
<div>
<label for="startDate">Start date: </label>
<input type="text"
name="startDate"
value="@Request["startDate"]"
/>
@Html.ValidationMessage("startDate")
</div>
<div>
<input type="submit" value="Submit" class="submit" />
</div>
<div>
@if(IsPost){
<p>@Html.Raw(message)</p>
}
</div>
</form>
</body>
</html>
Notice the following details in this example:
The code checks that
coursenameis a required field by usingIsEmpty. The same if block also checks that the course name is not longer than 5 characters by testing theLengthproperty of the string:if (coursename.IsEmpty() || coursename.Length > 5)The code checks that the value for
creditsis an integer by using theAsIntmethod. In this case,AsIntis called with an optional value of -1. This value (-1) will be returned if thecreditsvalue is not an integer. (You can assume that a valid value for credits is zero or greater.) You can then combine the result of theAsInttest with a range check:credits = Request["credits"].AsInt(-1);
// If the value is not an integer, -1 is returned.
if(credits < 1 || credits > 5)The value of
startDateis checked by usingAsDateTime. If the value cannot be converted to a date, theAsDateTimemethod returns a known value, namelyDateTime.MinValue. TheDateTime.MinValueproperty represents the earliest possible value that theDateTimeclass supports. It's far earlier than any valid value could be for thestartDatevalue.In each case, if the validation test fails, the error is "registered" by calling
ModelState.AddError. This method populates a collection of error values. When you callModelState.AddError, you specify that affected input element and you pass an error message.The code uses
ModelState.IsValidto determine whether validation has passed. If there are any validation errors (that is, if the collection populated byModelState.AddErroris not empty), theModelState.IsValidmethod returns false. In that case, don't process the user input.To display errors that were registered by using
ModelState.AddError, you can use theHtml.ValidationSummaryandHtml.ValidationMessagehelpers.

Comments (0) RSS Feed