"ASP." A brief talk on data annotation and validation

Source: Internet
Author: User

"01" About Google Chrome (theory)

"02" About Google Chrome (action) (top)

"03" About Google Chrome (operation) (bottom)

"04" On ASP. NET Framework

"05" A brief talk on ASP operation process

"06" On ASP. NET MVC Controller

"07" On ASP. NET MVC route

"08" On ASP. NET MVC View

"09" Talking about ASP. NET MVC view and controller passing data

"10" on Jqgrid in ASP.

"11" Several ways to transfer values between ASP.

"12" on the application of cache technology in ASP

"13" On the use of NuGet in VS

"14" on the publishing process of ASP

"15" on data annotation and verification

"16" talking about dependency Injection

"17" on forms and HTML-assisted methods

"18" discussion on Aps.net based authentication

"19" on ASP. NET MVC model

"20" Talking about ASP unit test

"21" On ASP. NET MVC network security;

"22" On the eight-class extension of ASP.

"23" Again on ASP. NET MVC Routing

"24" on the high-level topic of ASP

"25" on large ASP. NET MVC project (including demo)

"26" Next series: ASP. NET WebAPI

An overview

Data validation and data annotations are the necessary modules for any software system, which plays an important role in the software system.

1. From the verification of data validation, we generally divided into the client-side authentication and server authentication (or the combination of two methods);

2. From the point of view of data validation, data validation plays an important role, such as preventing vulnerability injection, preventing network attacks (XSS, etc.), ensuring data security, ensuring data rationality, and preventing garbage data.

3. From the type of data validation carcass, generally divided into third-party verification (such as we use jquery to write validation plug-in, the client with Ajax authentication) and the ASP-based data validation framework;

4. From the point of view of data annotations, such as the interface key fields of friendly settings and prompts, etc.;

Having said so much, what will be covered in this article?

This article focuses on the data validation features and data annotations based on the ASP. NET MVC framework.

Two-data verification

(i) ASP. Six types of data validation features built into the net MVC

1. In ASP. NET MVC, the validation attribute is defined in the System.ComponentModel.DataAnnotations namespace, so we need to introduce a namespace before using the validation feature:

Using System.ComponentModel.DataAnnotations;

2.asp.net MVC includes six validation features: Required,stringlength,regularexpression,range,compare and remote;

3. Data validation uses a single validation feature: Exponential authentication uses only one of the validation features

1 [required]2 Public  string Username {get; set;}

4. Some properties, a single validation feature cannot be met, require two or more combinations of authentication features, such as passwords, to satisfy at least two conditions:

(1) required (2) not less than 6 people

[Required] [Stringlength (6)] public string Password {get; set;}

5. Demonstrate five validation features in code (except remote)

Models:UserInfo.cs

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 using System.compo Nentmodel.dataannotations;         7 8 9 Namespace Datavalidate.models10 {One-to-public class UserInfo12 {13//define user name required [required]15 public string UserName {get; set;} 16//Define password required and meet 6-bit [required]18 [Stringlength (128,minimumlength =6)]19 public string Pass Word {get; set;} 20//Verify that the password for two times is consistent. [Required]22 [Compare ("Password", errormessage = "Two times password input inconsistent")]23 Publ IC string ConfirmPassword {get; set;} 24//Definition mail is required and the message format is met [required]26 [RegularExpression (@] [a-za-z0-9._%+-][email protected][a- Za-z0-9.-]+\. [A-za-z] {2,4} ")]27 public string Email {get; set;} 28//Definition age is required and between 1-130 years old [required]30 [Range (1,)]31 public int ages {get; set;} }33}34 

Controller:defaultcontroller

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using SYSTEM.WEB.MVC; 6  7 using Datavalidate.models; 8 namespace Datavalidate.controllers 9 {Ten Public     class Defaultcontroller:contro Ller11     {         //get:default13 public         ActionResult Index () () () ()             :         19 Public         ActionResult Datavalidatedemo (UserInfo UserInfo)             { UserInfo _userinfo = new UserInfo ();             _userinfo.username = userinfo.username;23             return View ("Index"); 24         }25     }26}

View:Index.cshtml

1 @model DataValidate.Models.UserInfo 2  3  4 @{5     viewbag.title = "Index"; 6} 7  8 

Let's take a look at the test results

6. Why should remote be singled out and explained separately?

We know that five authentication features except remote, namespaces are System.ComponentModel.DataAnnotations, and the namespace of the remote attribute is SYSTEM.WEB.MVC.

Remote, from the literal meaning can be seen, "remotely", that is, remote authentication. The remote feature means that the client's validation logic is executed using the server-side callback function (the action under the appropriate controller is automatically invoked when the metadata for the remote attribute is executed).

For example: When a new member registers, the general mobile phone number is not allowed to repeat, check the DB has a mobile phone number, you can use the remote feature to verify.

Model:UserInfo.cs

 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 6 using System.ComponentModel.DataAnnotations;         7 8 9 Namespace Datavalidate.models10 {One-to-public class UserInfo12 {13//define user name required [required]15 public string UserName {get; set;} 16//Define password required and meet 6-bit [required]18 [Stringlength (128,minimumlength =6)]19 public string Pass Word {get; set;} 20//Verify that the password for two times is consistent. [Required]22 [Compare ("Password", errormessage = "Two times password input inconsistent")]23 Publ IC string ConfirmPassword {get; set;} 24//Definition mail is required and the message format is met [required]26 [RegularExpression (@] [a-za-z0-9._%+-][email protected][a- Za-z0-9.-]+\. [A-za-z] {2,4} ")]27 public string Email {get; set;} 28//Definition age is required and between 1-130 years old [required]30 [Range (1,)]31 public int ages {get; set;} [Required]34 [System.Web.Mvc.Remote ("Checktelephone", "DEfault ", errormessage =" mobile number already exists ")]35 public string Telephone {get; set;}   36}37}38 39

Defaultcontroller

1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using SYSTEM.WEB.MVC; 6  7 using Datavalidate.models; 8 namespace Datavalidate.controllers 9 {Ten Public     class Defaultcontroller:contro Ller11     {         //get:default13 public         ActionResult Index () () () ()             :         19 Public         ActionResult Datavalidatedemo (UserInfo UserInfo)             { UserInfo _userinfo = new UserInfo ();             _userinfo.username = userinfo.username;23             return View ("Index"); 24         }25 public         actionresult Checktelephone (String telephone) (             telephone== "13636595489") )             {                 return JSON ("Phone number" +telephone+ "already exists", jsonrequestbehavior.allowget),             }32             return JSON ( True, Jsonrequestbehavior.allowget);         }35     }36}

Index.cshtml

 1 @model DataValidate.Models.UserInfo 2 3 4 @{5 viewbag.title = "Index"; 6 html.enableclientvalidation (); 7 Html.enableunobtrusivejavascript (); 8 9}10 

Test results:

Leave a study questions for everyone: how do I validate multiple parameters?

In the actual project development, we generally verify not only a parameter, but a number of parameters, such as user name and mobile phone number, identification number, such as verification, about the multi-parameter verification, remote verification features and how to deal with it?

(ii) Validation error notification

1. What is a validation error prompt?

Refers to the validation field when the validation does not pass, feedback to the user's prompt information, such as password can not be less than 6 digits, mobile phone number must be 11-bit, age limit between 1-130 years of age, etc., by verifying the characteristics of the erromessage implementation.

[Required] [Stringlength (128,minimumlength =6,errormessage = "Password cannot be less than 6 digits")]

2. Error verification hints are broadly divided into two broad categories: Default and custom error prompts.

(1) Default error message: When we do not specify a value for Erromessage, the ASP. NET MVC framework specifies a default value.

The definition password is required and satisfies 6-bit [Required][stringlength (128,minimumlength =6)] public string Password {get; set;}

Result:

(2) Custom value: We specify a specific custom value for errormessage "Password must not be less than 6 digits"

[Required] [Stringlength (128,minimumlength =6,errormessage = "Password cannot be less than 6 digits")] public string Password {get; set;}

Result:

3. Why do I need to have a custom error prompt?

(1) For users to present friendly hints, we look at the default values in 2 and the custom values;

Default value: Field password must be a string with a minimum length of 6 and a maximum length of 128 (so a word, if the user does not understand the program, it will certainly go insane,

Quite simply, for programmers, the word "field" is no longer basic, but to the user, he may ask, what is the field? )

Custom value: Password can not be less than 6 digits (both programmer and user can see clearly)

(2) To improve the universality, such as to provide English tips to the United States, Russia to provide Russian tips;

4. How to achieve universal internationalization?

In the custom validation error prompt as above, we are using hard-coded form, however, this hard-coded error message hint is impractical for international market development, because we want to show for different regions

Different content, to achieve internationalization, fortunately, all validation features allow for localized error message prompts to specify the resource type name and resource name, interested readers, please refer to how to:set the

Cultrue and UI cultrue for ASP. Page Globalization (sites:http://msdn.microsoft.com/en-us/library/bz9tc508.aspx)

Study questions, how to implement error message commonality internationalization?

(iii) Principle of verification

With regard to data validation, we are thinking about the question: When did validation happen? How can I know if the validation failed?

In this section we will answer this question.

1. To fully understand the principle of validation, we should first familiarize ourselves with a few basic concepts: Model binders, model metadata, model validators and model states (this part, this article does not discuss, you know that these concepts can, specific details of the content,

will be shared with you in the next article: "ASP. ASP. NET MVC Model"

2. By default, the ASP. NET MVC framework performs validation logic at the time of model binding and is divided into implicit execution and display execution when performing validation.

(1) Implicit execution: The model validation is implicitly performed when the Controller's action is accompanied by an argument. The following methods have parameters, so model binding is performed implicitly.

1 public actionresult Datavalidatedemo (UserInfo UserInfo) 2         {3             UserInfo _userinfo = new UserInfo (); 4             _ Userinfo.username = userinfo.username;5             return View ("Index"); 6         }

(2) Display execution: Displays execution model bindings only when the controller's Updatemodel or TryUpdateModel mode is used.

3. Model Binder Once the model properties are updated with the new values, the current model metadata is used to obtain all the validators for the model;

4.asp.net MVC Runtime, Dataannotationsmodelvalidator works with data validation;

The 5.DataAnnotationsModelValidator validator finds all the validation features and executes the validation logic it contains;

6. The model binder captures all failed validation rules and puts them into the model State;

7. The main byproduct of model binding is the state of the model, which contains the following content:

(1) contains all the values that the user puts into the model's properties;

(2) contains all errors associated with each attribute;

(3) contains all errors related to the model object itself;

8. If there is an error in the model state, MODELSTATE.ISVALID returns false;

9. How are control actions and validation errors performed?

The controller operation determines the execution process when the model validation fails and the validation succeeds.

(1) When validation is successful: when validated, the operation usually performs the necessary steps to save or update the user information;

(2) When validation fails: When validation fails, the operation will generally re-render the submission model worth the view;

(iv) Custom validation

The reason that ASP. NET MVC is powerful is that it provides strong customization and extensibility, which will be discussed in further articles: "The Sp.net MVC series" On the eight categories of ASP. NET MVC extension ".

1. Custom validation based on ASP. NET MVC is generally divided into two main types: encapsulating the validation logic in custom data and encapsulating the validation logic in the model object.

(1) Encapsulating the validation logic in custom data: complex, but high reusability;

(2) The validation logic is encapsulated in the model object: simple, but the reusability is low;

2. Encapsulate the validation logic in custom data (in a later article: "ASP. ASP.)" An introduction to the eight-class extension of the net MVC series "

3. Enclose the validation logic in the Model object (in the following article: "The ASP." "An introduction to the eight-class extension of ASP. NET MVC")

Three data annotations

(i) Seven types of ASP. NET MVC built-in data annotations

1.Dispaly Features: (1) model properties set a friendly display name (2) controls the order in which properties are displayed on the UI;

2.ScaffoldColumn Features: Hide HTML helper method;

3.DisplayFormat Features: Various formatting options for handling attributes;

4.ReadOnly Features: Ensure that the default model binder does not update with the new values;

5.DataType Feature: Provides specific information about the attribute;

6.UIHint Features: (1) provide the template name for the ASP runtime, in case the template helper method is invoked to render the output using the (2) Custom template helper method;

7.HiddenInput feature: Renders an element of type hidden;

Four reference documents

"01" ASP. MVC5 Advanced Programming (Jon Galloway,brad Wilson,k.scott allen,david Matson, Sun translation)

"02" ASP MVC5 Programming (3rd edition) (Dino esposite, Panli translation)

Five copyright areas

    • Thank you for your reading, if there are shortcomings, welcome advice, common learning and common progress.
    • Bo main website: http://www.cnblogs.com/wangjiming/.
    • A very small number of articles using reading, reference, reference, copying, copying and pasting into a variety of ways, most of the original.
    • If you like, please recommend, if you have new ideas, welcome, email: [Email protected].
    • The blog can be reproduced, but must be well-known from the blog source.

"ASP." A brief talk on data annotation and validation

Related Article

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.