"
 
 
 
ASP.NET (snapshot 2017) Microsoft documentation and samples

Introduction to model validation in ASP.NET Core MVC

By Rachel Appel

Introduction to model validation

Before an app stores data in a database, the app must validate the data. Data must be checked for potential security threats, verified that it is appropriately formatted by type and size, and it must conform to your rules. Validation is necessary although it can be redundant and tedious to implement. In MVC, validation happens on both the client and server.

Fortunately, .NET has abstracted validation into validation attributes. These attributes contain validation code, thereby reducing the amount of code you must write.

View or download sample from GitHub.

Validation Attributes

Validation attributes are a way to configure model validation so it’s similar conceptually to validation on fields in database tables. This includes constraints such as assigning data types or required fields. Other types of validation include applying patterns to data to enforce business rules, such as a credit card, phone number, or email address. Validation attributes make enforcing these requirements much simpler and easier to use.

Below is an annotated Movie model from an app that stores information about movies and TV shows. Most of the properties are required and several string properties have length requirements. Additionally, there is a numeric range restriction in place for the Price property from 0 to $999.99, along with a custom validation attribute.

[!code-csharpMain]

   1:  using System;
   2:  using System.ComponentModel.DataAnnotations;
   3:   
   4:  namespace MVCMovie.Models
   5:  {
   6:      public class Movie
   7:      {
   8:          public int Id { get; set; }
   9:   
  10:          [Required]
  11:          [StringLength(100)]
  12:          public string Title { get; set; }
  13:   
  14:          [ClassicMovie(1960)]
  15:          [DataType(DataType.Date)]
  16:          public DateTime ReleaseDate { get; set; }
  17:   
  18:          [Required]
  19:          [StringLength(1000)]
  20:          public string Description { get; set; }
  21:   
  22:          [Range(0, 999.99)]
  23:          public decimal Price { get; set; }
  24:   
  25:          [Required]
  26:          public Genre Genre { get; set; }
  27:   
  28:          public bool Preorder { get; set; }
  29:      }
  30:  }

Simply reading through the model reveals the rules about data for this app, making it easier to maintain the code. Below are several popular built-in validation attributes:

MVC supports any attribute that derives from ValidationAttribute for validation purposes. Many useful validation attributes can be found in the System.ComponentModel.DataAnnotations namespace.

There may be instances where you need more features than built-in attributes provide. For those times, you can create custom validation attributes by deriving from ValidationAttribute or changing your model to implement IValidatableObject.

Notes on the use of the Required attribute

Non-nullable value types (such as decimal, int, float, and DateTime) are inherently required and don’t need the Required attribute. The app performs no server-side validation checks for non-nullable types that are marked Required.

MVC model binding, which isn’t concerned with validation and validation attributes, rejects a form field submission containing a missing value or whitespace for a non-nullable type. In the absence of a BindRequired attribute on the target property, model binding ignores missing data for non-nullable types, where the form field is absent from the incoming form data.

The BindRequired attribute (also see (xref:)Customize model binding behavior with attributes) is useful to ensure form data is complete. When applied to a property, the model binding system requires a value for that property. When applied to a type, the model binding system requires values for all of the properties of that type.

When you use a Nullable<T> type (for example, decimal? or System.Nullable<decimal>) and mark it Required, a server-side validation check is performed as if the property were a standard nullable type (for example, a string).

Client-side validation requires a value for a form field that corresponds to a model property that you’ve marked Required and for a non-nullable type property that you haven’t marked Required. Required can be used to control the client-side validation error message.

Model State

Model state represents validation errors in submitted HTML form values.

MVC will continue validating fields until reaches the maximum number of errors (200 by default). You can configure this number by inserting the following code into the ConfigureServices method in the Startup.cs file:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Builder;
   2:  using Microsoft.AspNetCore.Hosting;
   3:  using Microsoft.Extensions.Configuration;
   4:  using Microsoft.Extensions.DependencyInjection;
   5:  using Microsoft.Extensions.Logging;
   6:  using MVCMovie.Controllers;
   7:   
   8:  namespace MVCMovie
   9:  {
  10:      public class Startup
  11:      {
  12:          public Startup(IHostingEnvironment env)
  13:          {
  14:              var builder = new ConfigurationBuilder()
  15:                  .SetBasePath(env.ContentRootPath)
  16:                  .AddEnvironmentVariables();
  17:   
  18:              Configuration = builder.Build();
  19:          }
  20:   
  21:          public IConfigurationRoot Configuration { get; }
  22:   
  23:          public void ConfigureServices(IServiceCollection services)
  24:          {
  25:              services.AddSingleton(new MVCMovieContext());
  26:              services.AddSingleton<IUserRepository>(new UserRepository());
  27:              services.AddMvc(options => options.MaxModelValidationErrors = 50);
  28:          }
  29:   
  30:          public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
  31:          {
  32:              loggerFactory
  33:                  .AddConsole(Configuration.GetSection("Logging"))
  34:                  .AddDebug();
  35:   
  36:              app.UseStaticFiles();
  37:              app.UseMvc(routes => routes.MapRoute(
  38:                  name: "default",
  39:                  template: "{controller=Movies}/{action=Index}/{id:int?}"));
  40:          }
  41:      }
  42:  }

Handling Model State Errors

Model validation occurs prior to each controller action being invoked, and it is the action method’s responsibility to inspect ModelState.IsValid and react appropriately. In many cases, the appropriate reaction is to return some kind of error response, ideally detailing the reason why model validation failed.

Some apps will choose to follow a standard convention for dealing with model validation errors, in which case a filter may be an appropriate place to implement such a policy. You should test how your actions behave with valid and invalid model states.

Manual validation

After model binding and validation are complete, you may want to repeat parts of it. For example, a user may have entered text in a field expecting an integer, or you may need to compute a value for a model’s property.

You may need to run validation manually. To do so, call the TryValidateModel method, as shown here:

[!code-csharpMain]

   1:  using System;
   2:  using Microsoft.AspNetCore.Mvc;
   3:  using MVCMovie.Models;
   4:   
   5:  namespace MVCMovie.Controllers
   6:  {
   7:      public class MoviesController : Controller
   8:      {
   9:          private readonly MVCMovieContext _context;
  10:   
  11:          public MoviesController(MVCMovieContext context)
  12:          {
  13:              _context = context;
  14:          }
  15:   
  16:          public IActionResult Index()
  17:          {
  18:              return View(_context.Movies);
  19:          }
  20:   
  21:          public IActionResult Create()
  22:          {
  23:              return View();
  24:          }
  25:   
  26:          [HttpPost]
  27:          [ValidateAntiForgeryToken]
  28:          public IActionResult Create(
  29:              string title,
  30:              Genre genre,
  31:              DateTime releaseDate,
  32:              string description,
  33:              decimal price,
  34:              bool preorder)
  35:          {
  36:              var modifiedReleaseDate = releaseDate;
  37:              if (releaseDate == null)
  38:              {
  39:                  modifiedReleaseDate = DateTime.Today;
  40:              }
  41:   
  42:              var movie = new Movie
  43:              {
  44:                  Title = title,
  45:                  Genre = genre,
  46:                  ReleaseDate = modifiedReleaseDate,
  47:                  Description = description,
  48:                  Price = price,
  49:                  Preorder = preorder,
  50:              };
  51:   
  52:              TryValidateModel(movie);
  53:              if (ModelState.IsValid)
  54:              {
  55:                  _context.AddMovie(movie);
  56:                  _context.SaveChanges();
  57:   
  58:                  return RedirectToAction(actionName: nameof(Index));
  59:              }
  60:   
  61:              return View(movie);
  62:          }
  63:      }
  64:  }

Custom validation

Validation attributes work for most validation needs. However, some validation rules are specific to your business, as they’re not just generic data validation such as ensuring a field is required or that it conforms to a range of values. For these scenarios, custom validation attributes are a great solution. Creating your own custom validation attributes in MVC is easy. Just inherit from the ValidationAttribute, and override the IsValid method. The IsValid method accepts two parameters, the first is an object named value and the second is a ValidationContext object named validationContext. Value refers to the actual value from the field that your custom validator is validating.

In the following sample, a business rule states that users may not set the genre to Classic for a movie released after 1960. The [ClassicMovie] attribute checks the genre first, and if it is a classic, then it checks the release date to see that it is later than 1960. If it is released after 1960, validation fails. The attribute accepts an integer parameter representing the year that you can use to validate data. You can capture the value of the parameter in the attribute’s constructor, as shown here:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:  using System.Globalization;
   5:  using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
   6:   
   7:  namespace MVCMovie.Models
   8:  {
   9:      public class ClassicMovieAttribute : ValidationAttribute, IClientModelValidator
  10:      {
  11:          private int _year;
  12:   
  13:          public ClassicMovieAttribute(int Year)
  14:          {
  15:              _year = Year;
  16:          }
  17:   
  18:          protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  19:          {
  20:              Movie movie = (Movie)validationContext.ObjectInstance;
  21:   
  22:              if (movie.Genre == Genre.Classic && movie.ReleaseDate.Year > _year)
  23:              {
  24:                  return new ValidationResult(GetErrorMessage());
  25:              }
  26:   
  27:              return ValidationResult.Success;
  28:          }
  29:   
  30:          public void AddValidation(ClientModelValidationContext context)
  31:          {
  32:              if (context == null)
  33:              {
  34:                  throw new ArgumentNullException(nameof(context));
  35:              }
  36:   
  37:              MergeAttribute(context.Attributes, "data-val", "true");
  38:              MergeAttribute(context.Attributes, "data-val-classicmovie", GetErrorMessage());
  39:   
  40:              var year = _year.ToString(CultureInfo.InvariantCulture);
  41:              MergeAttribute(context.Attributes, "data-val-classicmovie-year", year);
  42:          }
  43:   
  44:          private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
  45:          {
  46:              if (attributes.ContainsKey(key))
  47:              {
  48:                  return false;
  49:              }
  50:   
  51:              attributes.Add(key, value);
  52:              return true;
  53:          }
  54:   
  55:          private string GetErrorMessage()
  56:          {
  57:              return $"Classic movies must have a release year earlier than {_year}.";
  58:          }
  59:      }
  60:  }

The movie variable above represents a Movie object that contains the data from the form submission to validate. In this case, the validation code checks the date and genre in the IsValid method of the ClassicMovieAttribute class as per the rules. Upon successful validation IsValid returns a ValidationResult.Success code, and when validation fails, a ValidationResult with an error message. When a user modifies the Genre field and submits the form, the IsValid method of the ClassicMovieAttribute will verify whether the movie is a classic. Like any built-in attribute, apply the ClassicMovieAttribute to a property such as ReleaseDate to ensure validation happens, as shown in the previous code sample. Since the example works only with Movie types, a better option is to use IValidatableObject as shown in the following paragraph.

Alternatively, this same code could be placed in the model by implementing the Validate method on the IValidatableObject interface. While custom validation attributes work well for validating individual properties, implementing IValidatableObject can be used to implement class-level validation as seen here.

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:   
   5:  namespace MVCMovie.Models
   6:  {
   7:      public class MovieIValidatable : IValidatableObject
   8:      {
   9:          private const int _classicYear = 1960;
  10:   
  11:          public int Id { get; set; }
  12:   
  13:          [Required]
  14:          [StringLength(100)]
  15:          public string Title { get; set; }
  16:   
  17:          [Required]
  18:          public DateTime ReleaseDate { get; set; }
  19:   
  20:          [Required]
  21:          [StringLength(1000)]
  22:          public string Description { get; set; }
  23:   
  24:          [Range(0, 999.99)]
  25:          public decimal Price { get; set; }
  26:   
  27:          [Required]
  28:          public Genre Genre { get; set; }
  29:   
  30:          public bool Preorder { get; set; }
  31:   
  32:          public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
  33:          {
  34:              if (Genre == Genre.Classic && ReleaseDate.Year > _classicYear)
  35:              {
  36:                  yield return new ValidationResult(
  37:                      $"Classic movies must have a release year earlier than {_classicYear}.",
  38:                      new[] { "ReleaseDate" });
  39:              }
  40:          }
  41:      }
  42:  }

Client side validation

Client side validation is a great convenience for users. It saves time they would otherwise spend waiting for a round trip to the server. In business terms, even a few fractions of seconds multiplied hundreds of times each day adds up to be a lot of time, expense, and frustration. Straightforward and immediate validation enables users to work more efficiently and produce better quality input and output.

You must have a view with the proper JavaScript script references in place for client side validation to work as you see here.

[!code-cshtmlMain]

   1:  <!DOCTYPE html>
   2:  <html>
   3:  <head>
   4:      <meta charset="utf-8" />
   5:      <meta name="viewport" content="width=device-width, initial-scale=1.0">
   6:      <title>@ViewData["Title"] - MVC Movies</title>
   7:   
   8:      <link rel="stylesheet" href="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/css/bootstrap.min.css" />
   9:      <link rel="stylesheet" href="~/Site.css" />
  10:      <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.8.3.js"></script>
  11:  </head>
  12:  <body>
  13:      <div class="navbar navbar-inverse navbar-fixed-top">
  14:          <div class="container">
  15:              <div class="navbar-header">
  16:                  <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
  17:                      <span class="icon-bar"></span>
  18:                      <span class="icon-bar"></span>
  19:                  </button>
  20:                   @Html.ActionLink("MVC Movies", "Index", "Movies", new { area = "" }, new { @class = "navbar-brand" })
  21:              </div>
  22:              <div class="navbar-collapse collapse">
  23:                  <ul class="nav navbar-nav">
  24:                      <li>@Html.ActionLink("Home", actionName: "Index", controllerName: "Movies")</li>
  25:                      <li>@Html.ActionLink("Check email", actionName: "CheckEmail", controllerName: "Users")</li>
  26:                  </ul>
  27:              </div>
  28:          </div>
  29:      </div>
  30:      <div class="container body-content">
  31:          @RenderBody()
  32:          <hr />
  33:          <footer>
  34:              <p>&copy; @DateTime.Now.Year - @ViewData["Title"]</p>
  35:          </footer>
  36:      </div>
  37:      <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.0.min.js"></script>
  38:      <script src="https://ajax.aspnetcdn.com/ajax/bootstrap/3.3.7/bootstrap.min.js"></script>
  39:      <script src="https://ajax.aspnetcdn.com/ajax/respond/1.4.2/respond.min.js"></script>
  40:      @RenderSection("scripts", required: false)
  41:  </body>
  42:  </html>

[!code-cshtmlMain]

   1:  <script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.16.0/jquery.validate.min.js"></script>
   2:  <script src="https://ajax.aspnetcdn.com/ajax/jquery.validation.unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>

The jQuery Unobtrusive Validation script is a custom Microsoft front-end library that builds on the popular jQuery Validate plugin. Without jQuery Unobtrusive Validation, you would have to code the same validation logic in two places: once in the server side validation attributes on model properties, and then again in client side scripts (the examples for jQuery Validate’s validate() method shows how complex this could become). Instead, MVC’s (xref:)Tag Helpers and (xref:)HTML helpers are able to use the validation attributes and type metadata from model properties to render HTML 5 data- attributes in the form elements that need validation. MVC generates the data- attributes for both built-in and custom attributes. jQuery Unobtrusive Validation then parses thes data- attributes and passes the logic to jQuery Validate, effectively “copying” the server side validation logic to the client. You can display validation errors on the client using the relevant tag helpers as shown here:

[!code-cshtmlMain]

   1:  @model Movie
   2:  @{
   3:      ViewData["Title"] = "Create";
   4:  }
   5:   
   6:  <h2>Create</h2>
   7:  <form asp-action="Create">
   8:      <div class="form-horizontal">
   9:          <h4>Movie</h4>
  10:          <hr />
  11:          <div asp-validation-summary="ModelOnly" class="text-danger"></div>
  12:          <div class="form-group">
  13:              <label asp-for="Title" class="col-md-2 control-label"></label>
  14:              <div class="col-md-10">
  15:                  <input asp-for="Title" class="form-control" />
  16:                  <span asp-validation-for="Title" class="text-danger"></span>
  17:              </div>
  18:          </div>
  19:          <div class="form-group">
  20:              <label asp-for="ReleaseDate" class="col-md-2 control-label"></label>
  21:              <div class="col-md-10">
  22:                  <input asp-for="ReleaseDate" class="form-control" />
  23:                  <span asp-validation-for="ReleaseDate" class="text-danger"></span>
  24:              </div>
  25:          </div>
  26:          <div class="form-group">
  27:              <label asp-for="Description" class="col-md-2 control-label"></label>
  28:              <div class="col-md-10">
  29:                  <input asp-for="Description" class="form-control" />
  30:                  <span asp-validation-for="Description" class="text-danger"></span>
  31:              </div>
  32:          </div>
  33:          <div class="form-group">
  34:              <label asp-for="Price" class="col-md-2 control-label"></label>
  35:              <div class="col-md-10">
  36:                  <input asp-for="Price" class="form-control" />
  37:                  <span asp-validation-for="Price" class="text-danger"></span>
  38:              </div>
  39:          </div>
  40:          <div class="form-group">
  41:              <label asp-for="Genre" class="col-md-2 control-label"></label>
  42:              <div class="col-md-10">
  43:                  <select asp-for="Genre" asp-items="@(Html.GetEnumSelectList<Genre>())" class="form-control"></select>
  44:                  <span asp-validation-for="Genre" class="text-danger"></span>
  45:              </div>
  46:          </div>
  47:          <div class="form-group">
  48:              <div class="col-md-offset-2 col-md-10">
  49:                  <div class="checkbox">
  50:                      <input asp-for="Preorder" />
  51:                      <label asp-for="Preorder"></label>
  52:                  </div>
  53:              </div>
  54:          </div>
  55:          <div class="form-group">
  56:              <div class="col-md-offset-2 col-md-10">
  57:                  <input type="submit" value="Create" class="btn btn-default" />
  58:              </div>
  59:          </div>
  60:      </div>
  61:  </form>
  62:   
  63:  <div>
  64:      <a asp-action="Index">Back to List</a>
  65:  </div>
  66:   
  67:  @section Scripts {
  68:      @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
  69:   
  70:      <script type="text/javascript">
  71:      $(function () {
  72:          jQuery.validator.addMethod('classicmovie',
  73:              function (value, element, params) {
  74:                  // Get element value. Classic genre has value '0'.
  75:                  var genre = $(params[0]).val(),
  76:                      year = params[1],
  77:                      date = new Date(value);
  78:                  if (genre && genre.length > 0 && genre[0] === '0') {
  79:                      // Since this is a classic movie, invalid if release date is after given year.
  80:                      return date.getFullYear() <= year;
  81:                  }
  82:   
  83:                  return true;
  84:              });
  85:   
  86:          jQuery.validator.unobtrusive.adapters.add('classicmovie',
  87:              [ 'element', 'year' ],
  88:              function (options) {
  89:                  var element = $(options.form).find('select#Genre')[0];
  90:                  options.rules['classicmovie'] = [element, parseInt(options.params['year'])];
  91:                  options.messages['classicmovie'] = options.message;
  92:              });
  93:      }(jQuery));
  94:      </script>
  95:  }

The tag helpers above render the HTML below. Notice that the data- attributes in the HTML output correspond to the validation attributes for the ReleaseDate property. The data-val-required attribute below contains an error message to display if the user doesn’t fill in the release date field. jQuery Unobtrusive Validation passes this value to the jQuery Validate required() method, which then displays that message in the accompanying <span> element.

Thus, client-side validation prevents submission until the form is valid. The Submit button runs JavaScript that either submits the form or displays error messages.

MVC determines type attribute values based on the .NET data type of a property, possibly overridden using [DataType] attributes. The base [DataType] attribute does no real server-side validation. Browsers choose their own error messages and display those errors however they wish, however the jQuery Validation Unobtrusive package can override the messages and display them consistently with others. This happens most obviously when users apply [DataType] subclasses such as [EmailAddress].

Adding Validation to Dynamic Forms:

Because jQuery Unobtrusive Validation passes validation logic and parameters to jQuery Validate when the page first loads, dynamically generated forms will not automatically exhibit validation. Instead, you must tell jQuery Unobtrusive Validation to parse the dynamic form immediately after creating it. For example, the code below shows how you might set up client side validation on a form added via AJAX.

The $.validator.unobtrusive.parse() method accepts a jQuery selector for its one argument. This method tells jQuery Unobtrusive Validation to parse the data- attributes of forms within that selector. The values of those attributes are then passed to the jQuery Validate plugin so that the form exhibits the desired client side validation rules.

Adding Validation to Dynamic Controls:

You can also update the validation rules on a form when individual controls, such as <input/>s and <select/>s, are dynamically generated. You cannot pass selectors for these elements to the parse() method directly because the surrounding form has already been parsed and will not update. Instead, you first remove the existing validation data, then reparse the entire form, as shown below:

IClientModelValidator

You may create client side logic for your custom attribute, and unobtrusive validation will execute it on the client for you automatically as part of validation. The first step is to control what data- attributes are added by implementing the IClientModelValidator interface as shown here:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:  using System.Globalization;
   5:  using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
   6:   
   7:  namespace MVCMovie.Models
   8:  {
   9:      public class ClassicMovieAttribute : ValidationAttribute, IClientModelValidator
  10:      {
  11:          private int _year;
  12:   
  13:          public ClassicMovieAttribute(int Year)
  14:          {
  15:              _year = Year;
  16:          }
  17:   
  18:          protected override ValidationResult IsValid(object value, ValidationContext validationContext)
  19:          {
  20:              Movie movie = (Movie)validationContext.ObjectInstance;
  21:   
  22:              if (movie.Genre == Genre.Classic && movie.ReleaseDate.Year > _year)
  23:              {
  24:                  return new ValidationResult(GetErrorMessage());
  25:              }
  26:   
  27:              return ValidationResult.Success;
  28:          }
  29:   
  30:          public void AddValidation(ClientModelValidationContext context)
  31:          {
  32:              if (context == null)
  33:              {
  34:                  throw new ArgumentNullException(nameof(context));
  35:              }
  36:   
  37:              MergeAttribute(context.Attributes, "data-val", "true");
  38:              MergeAttribute(context.Attributes, "data-val-classicmovie", GetErrorMessage());
  39:   
  40:              var year = _year.ToString(CultureInfo.InvariantCulture);
  41:              MergeAttribute(context.Attributes, "data-val-classicmovie-year", year);
  42:          }
  43:   
  44:          private bool MergeAttribute(IDictionary<string, string> attributes, string key, string value)
  45:          {
  46:              if (attributes.ContainsKey(key))
  47:              {
  48:                  return false;
  49:              }
  50:   
  51:              attributes.Add(key, value);
  52:              return true;
  53:          }
  54:   
  55:          private string GetErrorMessage()
  56:          {
  57:              return $"Classic movies must have a release year earlier than {_year}.";
  58:          }
  59:      }
  60:  }

Attributes that implement this interface can add HTML attributes to generated fields. Examining the output for the ReleaseDate element reveals HTML that is similar to the previous example, except now there is a data-val-classicmovie attribute that was defined in the AddValidation method of IClientModelValidator.

Unobtrusive validation uses the data in the data- attributes to display error messages. However, jQuery doesn’t know about rules or messages until you add them to jQuery’s validator object. This is shown in the example below that adds a method named classicmovie containing custom client validation code to the jQuery validator object.

[!code-javascriptMain]

   1:  @model Movie
   2:  @{
   3:      ViewData["Title"] = "Create";
   4:  }
   5:   
   6:  <h2>Create</h2>
   7:  <form asp-action="Create">
   8:      <div class="form-horizontal">
   9:          <h4>Movie</h4>
  10:          <hr />
  11:          <div asp-validation-summary="ModelOnly" class="text-danger"></div>
  12:          <div class="form-group">
  13:              <label asp-for="Title" class="col-md-2 control-label"></label>
  14:              <div class="col-md-10">
  15:                  <input asp-for="Title" class="form-control" />
  16:                  <span asp-validation-for="Title" class="text-danger"></span>
  17:              </div>
  18:          </div>
  19:          <div class="form-group">
  20:              <label asp-for="ReleaseDate" class="col-md-2 control-label"></label>
  21:              <div class="col-md-10">
  22:                  <input asp-for="ReleaseDate" class="form-control" />
  23:                  <span asp-validation-for="ReleaseDate" class="text-danger"></span>
  24:              </div>
  25:          </div>
  26:          <div class="form-group">
  27:              <label asp-for="Description" class="col-md-2 control-label"></label>
  28:              <div class="col-md-10">
  29:                  <input asp-for="Description" class="form-control" />
  30:                  <span asp-validation-for="Description" class="text-danger"></span>
  31:              </div>
  32:          </div>
  33:          <div class="form-group">
  34:              <label asp-for="Price" class="col-md-2 control-label"></label>
  35:              <div class="col-md-10">
  36:                  <input asp-for="Price" class="form-control" />
  37:                  <span asp-validation-for="Price" class="text-danger"></span>
  38:              </div>
  39:          </div>
  40:          <div class="form-group">
  41:              <label asp-for="Genre" class="col-md-2 control-label"></label>
  42:              <div class="col-md-10">
  43:                  <select asp-for="Genre" asp-items="@(Html.GetEnumSelectList<Genre>())" class="form-control"></select>
  44:                  <span asp-validation-for="Genre" class="text-danger"></span>
  45:              </div>
  46:          </div>
  47:          <div class="form-group">
  48:              <div class="col-md-offset-2 col-md-10">
  49:                  <div class="checkbox">
  50:                      <input asp-for="Preorder" />
  51:                      <label asp-for="Preorder"></label>
  52:                  </div>
  53:              </div>
  54:          </div>
  55:          <div class="form-group">
  56:              <div class="col-md-offset-2 col-md-10">
  57:                  <input type="submit" value="Create" class="btn btn-default" />
  58:              </div>
  59:          </div>
  60:      </div>
  61:  </form>
  62:   
  63:  <div>
  64:      <a asp-action="Index">Back to List</a>
  65:  </div>
  66:   
  67:  @section Scripts {
  68:      @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
  69:   
  70:      <script type="text/javascript">
  71:      $(function () {
  72:          jQuery.validator.addMethod('classicmovie',
  73:              function (value, element, params) {
  74:                  // Get element value. Classic genre has value '0'.
  75:                  var genre = $(params[0]).val(),
  76:                      year = params[1],
  77:                      date = new Date(value);
  78:                  if (genre && genre.length > 0 && genre[0] === '0') {
  79:                      // Since this is a classic movie, invalid if release date is after given year.
  80:                      return date.getFullYear() <= year;
  81:                  }
  82:   
  83:                  return true;
  84:              });
  85:   
  86:          jQuery.validator.unobtrusive.adapters.add('classicmovie',
  87:              [ 'element', 'year' ],
  88:              function (options) {
  89:                  var element = $(options.form).find('select#Genre')[0];
  90:                  options.rules['classicmovie'] = [element, parseInt(options.params['year'])];
  91:                  options.messages['classicmovie'] = options.message;
  92:              });
  93:      }(jQuery));
  94:      </script>
  95:  }

Now jQuery has the information to execute the custom JavaScript validation as well as the error message to display if that validation code returns false.

Remote validation

Remote validation is a great feature to use when you need to validate data on the client against data on the server. For example, your app may need to verify whether an email or user name is already in use, and it must query a large amount of data to do so. Downloading large sets of data for validating one or a few fields consumes too many resources. It may also expose sensitive information. An alternative is to make a round-trip request to validate a field.

You can implement remote validation in a two step process. First, you must annotate your model with the [Remote] attribute. The [Remote] attribute accepts multiple overloads you can use to direct client side JavaScript to the appropriate code to call. The example below points to the VerifyEmail action method of the Users controller.

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc;
   2:   
   3:  namespace MVCMovie.Models
   4:  {
   5:      public class User
   6:      {
   7:          [Remote(action: "VerifyEmail", controller: "Users")]
   8:          public string Email { get; set; }
   9:   
  10:          [Remote(action: "VerifyName", controller: "Users", AdditionalFields = nameof(LastName))]
  11:          public string FirstName { get; set; }
  12:          [Remote(action: "VerifyName", controller: "Users", AdditionalFields = nameof(FirstName))]
  13:          public string LastName { get; set; }
  14:      }
  15:  }

The second step is putting the validation code in the corresponding action method as defined in the [Remote] attribute. According to the jQuery Validate remote() method documentation:

The serverside response must be a JSON string that must be "true" for valid elements, and can be "false", undefined, or null for invalid elements, using the default error message. If the serverside response is a string, eg. "That name is already taken, try peter123 instead", this string will be displayed as a custom error message in place of the default.

The definition of the VerifyEmail() method follows these rules, as shown below. It returns a validation error message if the email is taken, or true if the email is free, and wraps the result in a JsonResult object. The client side can then use the returned value to proceed or display the error if needed.

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc;
   2:   
   3:  namespace MVCMovie.Controllers
   4:  {
   5:      public class UsersController : Controller
   6:      {
   7:          private readonly IUserRepository _userRepository;
   8:   
   9:          public UsersController(IUserRepository userRepository)
  10:          {
  11:              _userRepository = userRepository;
  12:          }
  13:   
  14:          public IActionResult CheckEmail()
  15:          {
  16:              return View();
  17:          }
  18:   
  19:          [AcceptVerbs("Get", "Post")]
  20:          public IActionResult VerifyEmail(string email)
  21:          {
  22:              if (!_userRepository.VerifyEmail(email))
  23:              {
  24:                  return Json($"Email {email} is already in use.");
  25:              }
  26:   
  27:              return Json(true);
  28:          }
  29:   
  30:          [AcceptVerbs("Get", "Post")]
  31:          public IActionResult VerifyName(string firstName, string lastName)
  32:          {
  33:              if (!_userRepository.VerifyName(firstName, lastName))
  34:              {
  35:                  return Json(data: $"A user named {firstName} {lastName} already exists.");
  36:              }
  37:   
  38:              return Json(data: true);
  39:          }
  40:      }
  41:  }

Now when users enter an email, JavaScript in the view makes a remote call to see if that email has been taken and, if so, displays the error message. Otherwise, the user can submit the form as usual.

The AdditionalFields property of the [Remote] attribute is useful for validating combinations of fields against data on the server. For example, if the User model from above had two additional properties called FirstName and LastName, you might want to verify that no existing users already have that pair of names. You define the new properties as shown in the following code:

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc;
   2:   
   3:  namespace MVCMovie.Models
   4:  {
   5:      public class User
   6:      {
   7:          [Remote(action: "VerifyEmail", controller: "Users")]
   8:          public string Email { get; set; }
   9:   
  10:          [Remote(action: "VerifyName", controller: "Users", AdditionalFields = nameof(LastName))]
  11:          public string FirstName { get; set; }
  12:          [Remote(action: "VerifyName", controller: "Users", AdditionalFields = nameof(FirstName))]
  13:          public string LastName { get; set; }
  14:      }
  15:  }

AdditionalFields could have been set explicitly to the strings "FirstName" and "LastName", but using the nameof operator like this simplifies later refactoring. The action method to perform the validation must then accept two arguments, one for the value of FirstName and one for the value of LastName.

[!code-csharpMain]

   1:  using Microsoft.AspNetCore.Mvc;
   2:   
   3:  namespace MVCMovie.Controllers
   4:  {
   5:      public class UsersController : Controller
   6:      {
   7:          private readonly IUserRepository _userRepository;
   8:   
   9:          public UsersController(IUserRepository userRepository)
  10:          {
  11:              _userRepository = userRepository;
  12:          }
  13:   
  14:          public IActionResult CheckEmail()
  15:          {
  16:              return View();
  17:          }
  18:   
  19:          [AcceptVerbs("Get", "Post")]
  20:          public IActionResult VerifyEmail(string email)
  21:          {
  22:              if (!_userRepository.VerifyEmail(email))
  23:              {
  24:                  return Json($"Email {email} is already in use.");
  25:              }
  26:   
  27:              return Json(true);
  28:          }
  29:   
  30:          [AcceptVerbs("Get", "Post")]
  31:          public IActionResult VerifyName(string firstName, string lastName)
  32:          {
  33:              if (!_userRepository.VerifyName(firstName, lastName))
  34:              {
  35:                  return Json(data: $"A user named {firstName} {lastName} already exists.");
  36:              }
  37:   
  38:              return Json(data: true);
  39:          }
  40:      }
  41:  }

Now when users enter a first and last name, JavaScript:

If you need to validate two or more additional fields with the [Remote] attribute, you provide them as a comma-delimited list. For example, to add a MiddleName property to the model, set the [Remote] attribute as shown in the following code:

AdditionalFields, like all attribute arguments, must be a constant expression. Therefore, you must not use an interpolated string or call string.Join() to initialize AdditionalFields. For every additional field that you add to the [Remote] attribute, you must add another argument to the corresponding controller action method.





Comments ( )
<00>  <01>  <02>  <03>  <04>  <05>  <06>  <07>  <08>  <09>  <10>  <11>  <12>  <13>  <14>  <15>  <16>  <17>  <18>  <19>  <20>  <21>  <22>  <23
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnetcore/mvc/models/validation.htm
<SITEMAP>  <MVC>  <ASP>  <NET>  <DATA>  <KIOSK>  <FLEX>  <SQL>  <NOTES>  <LINUX>  <MONO>  <FREEWARE>  <DOCS>  <ENG>  <CHAT ME>  <ABOUT ME>  < THANKS ME>