About

I'm Mike Pope. I live in the Seattle area. I've been a technical writer and editor for over 30 years. I'm interested in software, language, music, movies, books, motorcycles, travel, and ... well, lots of stuff.

Read more ...

Blog Search


(Supports AND)

Google Ads

Feed

Subscribe to the RSS feed for this blog.

See this post for info on full versus truncated feeds.

Quote

People studying literature rarely say anything that would be of the slightest use to those producing it.

Paul Graham



Navigation





<December 2014>
SMTWTFS
30123456
78910111213
14151617181920
21222324252627
28293031123
45678910

Categories

  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  
  RSS  

Contact

Email me

Blog Statistics

Dates
First entry - 6/27/2003
Most recent entry - 11/24/2014

Totals
Posts - 2316
Comments - 2506
Hits - 1,693,488

Averages
Entries/day - 0.55
Comments/entry - 1.08
Hits/day - 404

Updated every 30 minutes. Last: 11:28 PM Pacific


  08:45 PM

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:
  1. 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.


  2. 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])


  3. 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
        }
    }


  4. 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")


  5. 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

[categories]   ,

|