ASP. MVC5 (iv): Data annotations and validation

Source: Internet
Author: User

Objective

The work of user input validation is performed not only in the client browser, but also on the server. The main reason is that client authentication gives immediate feedback to the input data, improves the user experience, and server-side validation, mainly because the user-supplied data is not fully trusted. The ASP. NET MVC Framework provides a powerful validation component to help us deal with these complex issues.

Use of data validation validation annotations

Validation annotation attribute definitions in namespace System.ComponentModel.DataAnnotations, which provide server-side validation, the framework also supports client validation when used on the properties of a model. Introduction to Common features:

    • Required
      When the value of the property is null or empty, a validation error is raised, which is understood to be required if the required attribute is added.
    • Stringlength
      Defines the string length.
    • RegularExpression
      Use regular expressions to verify that the input string conforms to the formatting requirements.
    • Range
      Used to specify the minimum and maximum values for the input values.
    • Compare
      Used to determine whether two properties have the same value. For example, make sure that you enter the same password two times.
    • Remote
      The client's logical validation is performed using a server-side callback function.

Below, a simple example is used to illustrate how these features work.
Suppose we now develop a library management system that creates a book class in the Models folder to hold the basic information of a book.

public class Book{    public int Id { get; set; }    public string Name { get; set; }    public string Author { get; set; }    public int PagesNumber { get; set; }    public string Publisher { get; set; }    public string PublicationDate { get; set; }    public string Content { get; set; }    public decimal Price { get; set; }    public decimal PriceConfirm { get; set; }}

Add Bookscontroller, launch the project, at this point, ASP. NET MVC has helped us to create the appropriate controller and view, direct the browser to the/books/create, to browse the following pages for adding a book.

When you add a book, the user wants to perform some validation of the input data and return an error message when the input data fails to pass the relevant validation. At this point, the validation annotation feature comes in handy.
The first step is to introduce a namespace

using System.ComponentModel.DataAnnotations;using System.Web.Mvc;

Add the Checkcontent method to Bookscontroller (to prepare for using the remote feature)

    public JsonResult CheckContent(string content)    {        var result = db.Books.Where(m => m.Content == content).Count() == 0;        return Json(result, JsonRequestBehavior.AllowGet);    }

Modify the book class to add validation annotations, respectively:

    public int Id { get; set; }    [Required] //必填    public string Name { get; set; }    [StringLength(50)] //作者姓名的长度不能超过50个字符    public string Author { get; set; }    [Range(100, 10000)] //页数保证在100~10000页之间    public int PagesNumber { get; set; }    public string Publisher { get; set; }    [RegularExpression(@"^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$")]   //日期格式    public string PublicationDate { get; set; }    [Remote("CheckContent", "Books")]   //内容介绍不能重复    public string Content { get; set; }    public decimal Price { get; set; }    [System.ComponentModel.DataAnnotations.Compare("Price")]  //两次输入的价格必须一致    public decimal PriceConfirm { get; set; }

Restart the project and enter data that does not conform to the validation logic on the Create page, with the following effect:

Re-enter the correct data, click Create, after the data entered successfully, we entered another book, content contents and the content of the last addition to the same, get error message, at this time the remote feature called the Checkcontent method to verify.

★注意,Remote特性自动发送AJAX请求访问后台代码来实现验证,它只有客户端验证,没有服务端验证。也就是说,当用户浏览器关闭js,Remote检查将不起作用,因此,Remote特性存在一定的安全隐患。同理,如果创建Controller时没有勾选Reference script libraries选项,Remote特性也将不起任何作用。

Custom Error Hints

Each validation attribute allows you to pass in a parameter with a custom error message, such as the error message returned by the RegularExpression attribute in the example above, and the user may not understand the meaning of the regular expression, at which point we need to return some easy-to-understand error messages. The errormessage parameter is passed to the regularexpression.

    [RegularExpression(@"^\d{4}(\-|\/|\.)\d{1,2}\1\d{1,2}$",ErrorMessage ="请输入有效的日期格式,例如:2017-06-16")]   //日期格式    public string PublicationDate { get; set; }

The effect is as follows:

Background principle and controller operation of verification annotations

By default, the ASP. NET MVC framework performs validation logic at the time of model binding. Once the model binder has updated the model properties with the new values, it takes advantage of the current model metadata to get all the validators for the model. The ASP. NET MVC Runtime provides a validator Dataannotationsmodelvalidator to work with data annotations. This model validator will find all the validation attributes and execute the validation logic they contain. The model binder captures all failed validation rules and stores them in the model state.

The controller operation determines the execution process of the program when the model validation fails or succeeds. Typically, validation succeeds, the user input data is saved, validation fails, the view is re-rendered, and an error message is returned. The following is the system automatically created by the Create method, first determine the model state modelstate whether there is an error, if not exist, save the book information, if there is a failure, then re-render the view.

    [HttpPost]    [ValidateAntiForgeryToken]    public ActionResult Create([Bind(Include = "Id,Name,Author,PagesNumber,Publisher,PublicationDate,Content,Price,PriceConfirm")] Book book)    {        if (ModelState.IsValid)        {            db.Books.Add(book);            db.SaveChanges();            return RedirectToAction("Index");        }        return View(book);    }

Custom validation Logic

The previous section describes so many validation annotations, we can not help but ask, users often come up with a lot of wonderful needs, can we define some of our own validation logic? The answer is yes. In this section, you will learn how to complete your custom logic validation.

Custom annotations

All validation annotation attributes are ultimately derived from the base class Validationattribute, which is an abstract class, so you must also derive from the Validationattribute class when creating custom annotation attributes.
Suppose the user puts forward a demand, because an author is ruthlessly banned, enter the book information, the author column can not be a designated name.

First, the addition of the Checkauthorattribute class derives from the base class Validationattribute:

using System.ComponentModel.DataAnnotations;namespace MyFirstMvcProject.Infrastructure{    public class CheckAuthorAttribute : ValidationAttribute    {    }}

To implement this validation, the IsValid method of the base class needs to be overridden, and the Validationcontext parameter provides information that can be used inside the IsValid method, such as model type, model object instance, the display name used to validate the property, and so on. The first parameter of the IsValid method is the value of the object to validate, and we get the name of the person that cannot be verified by the constructor.

public class CheckAuthorAttribute : ValidationAttribute{    public string Author { get; set; }    public CheckAuthorAttribute(string author) : base("{0} can not be this one. ")    {        this.Author = author;    }    protected override ValidationResult IsValid(object value, ValidationContext validationContext)    {        if (value != null)        {            if (value.ToString() == Author)            {                return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));            }        }        return ValidationResult.Success;    }}

The above code has two points to note:

    1. The basis function class constructor passes a default value for the error message.
    2. Formaterrormessage method: Apply formatting to the error message based on the data field where the comparison error occurred.

Modify the book class to add the Checkauthor attribute on the Author property.

    [StringLength(50)] //作者姓名的长度不能超过50个字符    [CheckAuthor("Thomas", ErrorMessage = "Author can not be this one.")]    public string Author { get; set; }

Run the program, enter author, click Create, the effect is as follows:

So far, we have successfully created custom annotation features, but the attentive user has found that the newly added validation can only be triggered when the create is clicked, and other validations give immediate feedback. As the user says, we've only added server-side validation at this time, and here's how to add client validation for the Checkauthor attribute.

Modify the Maxwordsattribute class so that it inherits the Iclientvalidatable interface, implementing the Getclientvalidationrules method.

  public class Checkauthorattribute:validationattribute, iclientvalidatable {public string Author {get; s Et    Public Checkauthorattribute (string author): Base ("{0} can is not is this one.") {this.    Author = Author; } protected override Validationresult IsValid (object value, Validationcontext validationcontext) {if (value ! = null) {if (value. ToString () = = Author) {return new Validationresult (Formaterrormessage (validationcontext.display            Name));    }} return validationresult.success; } public ienumerable<modelclientvalidationrule> Getclientvalidationrules (Modelmetadata metadata, ControllerContext context) {var rule = new Modelclientvalidationrule () {ValidationType = "Checkauthor", Errorm Essage = formaterrormessage (metadata.        GetDisplayName ())}; Rule.        Validationparameters.add ("author", author);    yield return rule; }}

Description

    1. The Iclientvalidatable interface provides a way for the ASP. NET MVC validation framework to discover whether the validator supports client-side validation at run time. Getclientvalidationrules is implemented in the class and returns the client validation rules for that class.
    2. The ErrorMessage property is used to hold the error message.
    3. The Validationparameters collection is used to hold the parameters required by the client, in this case Thomas.
    4. The ValidationType property identifies a piece of JavaScript code that the client needs.

Under the Scripts folder, add the JavaScript file, named Customvalidators.js, and type the following code:

/// <reference path="jquery.validate.js" />/// <reference path="jquery.validate.unobtrusive.js" />$.validator.addMethod("checkauthor", function (value, element, author) {    if (value) {        if (value == author) {            return false;        }    }    return true;});$.validator.unobtrusive.adapters.addSingleVal("checkauthor", "author");

Description

    1. Addsingleval creates an adapter for validation rules that need to retrieve unique parameter values from metadata. The first parameter is the adapter name, and the second parameter is the name of the parameter to retrieve from the metadata.
    2. Call Validator. The Addmethod method adds a new validator.

Finally, add a reference to the Customvalidators.js in views/books/create.cshtml:

@section Scripts {    @Scripts.Render("~/bundles/jqueryval")    <script src="~/Scripts/customValidators.js"></script>}

Start the program, position the URL to/books/create, enter Thomas in the author text box, and complete the validation when the focus leaves the author text box.

ASP. MVC5 (iv): Data annotations and validation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.