Validating User Input in ASP.Internet Web Pages (Razor) Sites

by Tom FitzMacken

This article discusses how to validate data yous get from users — that is, to make certain that users enter valid data 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 information that doesn't come directly from users.

These are the ASP.Net programming concepts introduced in the commodity:

  • The Validation helper.
  • The Html.ValidationSummary and Html.ValidationMessage methods.

Software versions used in the tutorial

  • ASP.NET Web Pages (Razor) 3

This tutorial also works with ASP.Internet Web Pages 2.

This article contains the post-obit sections:

  • Overview of User Input Validation
  • Validating User Input
  • Adding Customer-Side Validation
  • Formatting Validation Errors
  • Validating Data That Doesn't Come Straight from Users

Overview of User Input Validation

If you inquire 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 case, you don't want to process a course that'southward missing disquisitional information.

When users enter values into an HTML grade, the values that they enter are strings. In many cases, the values yous need are some other information types, similar integers or dates. Therefore, you also have to make certain that the values that users enter can be correctly converted to the advisable data types.

Y'all might too have certain restrictions on the values. Fifty-fifty if users correctly enter an integer, for example, yous might need to make sure that the value falls inside a certain range.

Validation errors that use CSS style classes

Notation

Of import Validating user input is too important for security. When y'all restrict the values that users can enter in forms, you reduce the hazard that someone can enter a value that tin can compromise the security of your site.

Validating User Input

In ASP.Internet Spider web Pages 2, you tin use the Validator helper to test user input. The basic approach is to practise the following:

  1. Determine which input elements (fields) you want to validate.

    Y'all typically validate values in <input> elements in a grade. However, it's a good practise to validate all input, fifty-fifty input that comes from a constrained element like a <select> list. This helps to brand sure that users don't bypass the controls on a folio and submit a course.

  2. In the page code, add individual validation checks for each input element past using methods of the Validation helper.

    To check for required fields, utilize Validation.RequireField(field, [fault bulletin]) (for an individual field) or Validation.RequireFields(field1, field2, ...)) (for a listing of fields). For other types of validation, use Validation.Add(field, ValidationType). For ValidationType, you tin use these options:

    Validator.DateTime ([error bulletin])
    Validator.Decimal([error message])
    Validator.EqualsTo(otherField [, mistake bulletin])
    Validator.Bladder([error message])
    Validator.Integer([error message])
    Validator.Range(min, max [, error bulletin])
    Validator.RegEx(pattern [, error bulletin])
    Validator.Required([fault message])
    Validator.StringLength(length)
    Validator.Url([fault message])

  3. When the folio is submitted, cheque whether validation has passed by checking Validation.IsValid:

                      if(IsPost && Validation.IsValid()){     // Procedure form submit }                                  

    If there are whatsoever validation errors, y'all skip normal page processing. For instance, if the purpose of the folio is to update a database, you don't practice that until all validation errors have been fixed.

  4. If there are validation errors, display error messages in the folio'southward markup by using Html.ValidationSummary or Html.ValidationMessage, or both.

The post-obit example shows a page that illustrates these steps.

              @{     var bulletin="";     // Specify validation requirements for different fields.     Validation.RequireField("coursename", "Course proper name is required");     Validation.RequireField("credits", "Credits is required");     Validation.Add together("coursename", Validator.StringLength(5));     Validation.Add together("credits", Validator.Integer("Credits must be an integer"));     Validation.Add("credits", Validator.Range(1, v, "Credits must be betwixt 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 Course, yous entered " + coursename;             message += @"<br/>For Credits, you entered " + credits.ToString();             message += @"<br/>For Showtime 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; }    </way> </head> <body>   <h1>Validation Example</h1>   <p>This example page asks the user to enter information nearly some classes at school.</p>   <class method="post">     @Html.ValidationSummary()     <div>       <label for="coursename">Course name: </characterization>       <input type="text"          name="coursename"          value="@Request["coursename"]"       />       @Html.ValidationMessage("coursename")     </div>      <div>       <label for="credits">Credits: </label>       <input blazon="text"          proper name="credits"          value="@Request["credits"]"       />       @Html.ValidationMessage("credits")     </div>      <div>       <label for="startDate">Showtime date: </label>       <input blazon="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 run across how validation works, run this page and deliberately brand mistakes. For example, hither's what the page looks like if you forget to enter a course proper noun, if you enter an, and if you enter an invalid engagement:

Validation errors in the rendered page

Adding Client-Side Validation

Past default, user input is validated later on users submit the folio — 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 circuitous, reporting errors just later the page is submitted tin can be inconvenient to the user.

Y'all tin 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 tin can likewise reduce the number of times that the user has to submit the form to right multiple errors.

Note

Even if you lot utilize customer-side validation, validation is always besides performed in server code. Performing validation in server code is a security measure, in case users featherbed client-based validation.

  1. Register the following JavaScript libraries in the folio:

                      <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js"> </script> <script src="https://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), and so y'all don't necessarily accept to have them on your computer or server. However, you lot must take a local copy of jquery.validate.unobtrusive.js. If you are non already working with a WebMatrix template (similar Starter Site ) that includes the library, create a Web Pages site that'due south based on Starter Site. Then copy the .js file to your electric current site.

  2. In markup, for each element that you're validating, add together a call to Validation.For(field). This method emits attributes that are used by customer-side validation. (Rather than emitting actual JavaScript lawmaking, the method emits attributes similar information-val-.... These attributes support unobtrusive customer validation that uses jQuery to do the work.)

The following page shows how to add customer validation features to the example shown earlier.

              @{     // Note that client validation as implemented here will work merely with     // ASP.NET Web Pages 2.      var message="";     // Specify validation requirements for unlike fields.     Validation.RequireField("coursename", "Class name is required");     Validation.RequireField("credits", "Credits is required");     Validation.Add together("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("Commencement date must be a date"));      if (IsPost)  {         // Before processing anything, make sure that all user input is valid.         if (Validation.IsValid()) {             var coursename = Asking["coursename"];             var credits = Request["credits"].AsInt();             var startDate = Asking["startDate"].AsDateTime();             message += @"For Course, you entered " + coursename;             message += @"<br/>For Credits, y'all entered " + credits.ToString();             message += @"<br/>For Start Date, yous 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="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js"></script>     <script         src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.i/jquery.validate.js">     </script>     <script src="~/Scripts/jquery.validate.unobtrusive.js"></script> </head> <body>   <h1>Validation Case with Client Validation</h1>   <p>This example folio asks the user to enter information well-nigh some classes at school.</p>   <form method="mail">     @Html.ValidationSummary()     <div>       <characterization for="coursename">Course proper name: </label>       <input type="text"          proper noun="coursename"          value="@Request["coursename"]"          @Validation.For("coursename")       />       @Html.ValidationMessage("coursename")     </div>      <div>       <label for="credits">Credits: </label>       <input type="text"          proper name="credits"          value="@Request["credits"]"          @Validation.For("credits")       />       @Html.ValidationMessage("credits")     </div>      <div>       <label for="startDate">Commencement date: </characterization>       <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>   </grade> </body> </html>                          

Not all validation checks run on the client. In particular, data-type validation (integer, appointment, and then on) don't run on the customer. The post-obit checks work on both the client and server:

  • Required
  • Range(minValue, maxValue)
  • StringLength(maxLength[, minLength])
  • Regex(blueprint)
  • EqualsTo(otherField)

In this example, the test for a valid date won't piece of work in customer code. Still, the test volition exist 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 the Html.ValidationMessage method when information technology's displaying an error.
  • field-validation-valid. Defines the output of the Html.ValidationMessage method when there is no mistake.
  • input-validation-error. Defines how <input> elements are rendered when there's an mistake. (For case, you lot tin can apply this grade to set up the background colour of an <input> element to a different color if its value is invalid.) This CSS grade is used only during client validation (in ASP.Net Web Pages ii).
  • input-validation-valid. Defines the appearance of <input> elements when at that place is no mistake.
  • validation-summary-errors. Defines the output of the Html.ValidationSummary method it'due south displaying a list of errors.
  • validation-summary-valid. Defines the output of the Html.ValidationSummary method when in that location is no error.

The following <mode> block shows rules for mistake weather.

              <style> .validation-summary-errors {   edge:2px solid red;   color:red;   font-weight:bold;   margin:6px;   width:30%; }  .field-validation-error{   color:red;    font-weight:bold;    background-color:xanthous; }  .input-validation-fault{   color:carmine;   font-weight:assuming;   background-color:pinkish; } </style>                          

If you include this style block in the example pages from earlier in the commodity, the error display volition look like the following illustration:

Validation errors that use CSS style classes

Notation

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 accept any effect.

Static and Dynamic Error Brandish

The CSS rules come in pairs, such equally validation-summary-errors and validation-summary-valid. These pairs allow yous ascertain rules for both conditions: an mistake condition and a "normal" (non-fault) condition. It'south important to empathize that the markup for the error brandish is always rendered, even if in that location are no errors. For example, if a page has an Html.ValidationSummary method in the markup, the page source volition comprise the following markup even when the folio is requested for the starting time time:

<div grade="validation-summary-valid" data-valmsg-summary="true"><ul></ul></div>

In other words, the Html.ValidationSummary method e'er renders a <div> element and a listing, even if the error list is empty. Similarly, the Html.ValidationMessage method always renders a <span> element as a placeholder for an individual field mistake, fifty-fifty if there is no error.

In some situations, displaying an error bulletin can cause the page to reflow and can cause elements on the page to move effectually. The CSS rules that cease in -valid let yous ascertain a layout that can help prevent this trouble. For instance, you tin can define field-validation-fault and field-validation-valid to both have the same fixed size. That mode, the brandish area for the field is static and won't change the page menses 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 cord, as in the following case:

http://server/myapp/EditClassInformation?classid=1022

In this case, you want to make sure that the value that'due south passed to the page (here, 1022 for the value of classid) is valid. You lot tin can't directly use the Validation helper to perform this validation. Even so, you lot tin apply other features of the validation system, like the ability to brandish validation error messages.

Notation

Important Always validate values that you lot get from any source, including form-field values, query-string values, and cookie values. It's like shooting fish in a barrel for people to change these values (perhaps for malicious purposes). So you must check these values in social club 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 non empty and that information technology's an integer.

              if(!IsPost){     if(!Request.QueryString["classid"].IsEmpty() && Asking.QueryString["classid"].IsInt()) {         // Process the value     }     else{         Validation.AddFormError("No class was selected.");     } }                          

Observe that the examination is performed when the request is not a form submission (if(!IsPost)). This exam would laissez passer the commencement time that the page is requested, merely 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 fault is displayed at that place, just similar a user-input validation error.

Additional Resource

Working with HTML Forms in ASP.Internet Spider web Pages Sites