In v1 of ASP.NET Web Pages, you could add user-input validation by doing something like this in code:
if (name.IsEmpty()) {
ModelState.AddError("Name", "You must enter a name.");
}
In v2, there's a new Validation
helper that has some nifty features:- Methods to check for required fields, data types, string length, numeric ranges, the same values in two fields (as for new passwords), and patterns (i.e., RegEx).
- Methods to display both field-specific and summary validation error messages.
- Both client-side (instant) and server-side (post-submit) validation. "A double dose of valid!" (#)
For client validation, you also get:- Unobtrusive JavaScript techniques to minimize client code in the file, relying instead on semantic attributes in the markup.
- No submit until all values are valid.
You can use the Validation
helper to provide only server-side validation or both client- and server-side checks. (You always get server validation, for security reasons.) The basic steps for server-side validation are:- Determine which input elements (fields) you want to validate
You typically validate values in <input>
elements in a form. However, it is a good practice to validate all input, even input that comes from a constrained element like a <select>
list, because users can bypass the controls on a page and submit a form.
- Add individual validation checks for each input element (field)
In the page's code block, call one of the methods of the Validation
helper that perform validation: RequireField
, RequireFields
, or Add
. Pass to the method the name (the name
attribute value) of the UI element that you want to validate. Do this for each field that you want to validate.
For example, to specify a required field, use calls like these:
Validation.RequireField("text1");
Validation.RequireField("text1", "The text1 field is required");
Validation.RequireFields("text1", "text2", "text3");
You can specify multiple fields at a time using RequireFields
, but that that method does not allow you to specify a custom error message.
To specify any other kind of validation, call Validation.Add
:
Validation.Add(field, ValidationType)
ValidationType is specified as a field of the Validator
type. Options include:
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])
- Check whether validation has passed
In code, call the Validation.IsValid
method to determine whether all UI elements have passed validation. You typically do this when processing a form submission.
if(IsPost){
if (Validation.IsValid()) {
// Process input
}
}
- Display a field-specific validation message (optional)
If you want to display an error message that's specific to one field, call the Html.ValidationMessage
method in markup right where you want the message to appear. Pass it the name of the field to display an error for, like this:
<input type="text"
name="coursename"
value="@Request["coursename"]" />
@Html.ValidationMessage("coursename")
- Display a summary of validation errors (optional)
If you want a summary listing of validation errors in addition to or instead of field-specific error messages, call the Html.ValidationSummary
method in markup right where you want the summary to appear. Like this:
<div>
@Html.ValidationSummary()
</div>
By default, the ValidationSummary
method displays a bulleted list (<ul>
element) with each error as an item. Various overloads of the method let you specify a custom error and attributes that are added to the markup generated by the helper.
Here's a page that implements this. Remember that this currently only performs server-side validation.
@{
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"));
if (IsPost) {
// Before processing anything, make sure that all user input is valid.
if (Validation.IsValid()) {
var coursename = Request["coursename"];
var credits = Request["credits"];
message += @"For Class, you entered " + coursename;
message += @"<br/>For Credits, you entered " + credits;
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<style>
body {margin: 1in; font-family: 'Segoe UI'; font-size: 11pt; }
#valSumContainer {color:Red; font-weight:bold;border: 1px red blue;}
</style>
</head>
<body>
<form method="post">
@Html.ValidationSummary(
"Please fix these errors",
true,
new Dictionary<string, object> { { "id", "valSumContainer" } }
)
<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>
<input type="submit" value="Submit" class="submit" />
</div>
<div>
@if(IsPost){
<p>@Html.Raw(message)</p>
}
</div>
</form>
</body>
</html>
Next time: Adding client functionality. Hint: it's simple.
See Also