Http://www.cnblogs.com/BingoLee/archive/2011/12/23/2298822.html
Objective:
No matter what kind of Web program you write, you need to validate your data to ensure the validity and completeness of your data.
The ASP. NET MVC3 allows you to perform data validation in a way called "Data annotations," which includes the client browser
and server-side two-step verification. Perhaps you ask why two validations? First, client-side validation can respond directly to customers, reducing service
Also improves the user experience, but you can never trust information from the client (the user may turn off the browser's scripting feature,
Make your JS verification completely ineffective), so server-side validation is also required. As shown in the following:
1, general validation (required field, string length, regular expression validation, range validation < value, Date >)
Let's look at an error message that adds feedback to the interface.
The entity class code is as follows:
<summary>///Employee Information//</summary>public class staffinfo{public virtual int staffinfoid {get; set;} [Required] [Display (Name = "login account")] public virtual string Logid {get; set;} [Stringlength (minimumlength = 4, errormessage = "{0} must have a length greater than {2} characters and less than {1} characters")] [Display (Name = "password")] public virtual string Logpassword {get; set;} [Stringlength (errormessage = "{0} cannot be longer than {1} characters")] [Display (name = "name")] public virtual string Realname {get; set;} [Display (Name = "date of birth")]//[range (typeof (DateTime), "2011-12-31", "1950-1-1", errormessage = "{0} range is {1} to {2}")] Publ IC virtual DateTime Birthday {get; set;} [RegularExpression (@ "\d{17}[\d| X]|\D{15} ", errormessage =" {0} is malformed ")] [Display (Name =" identity card number ")] public virtual string Identityno {get; set;} [RegularExpression (@ "[a-za-z0-9._%+-][email protected][a-za-z0-9.-]+\.[ a-za-z]{2,4} ", errormessage =" {0} is malformed ")] [Display (Name =" Mailbox ")] public virtual string Email {get; set;} [Display (Name = "tombstone identifier")] public virtual int Islogicdelete {get; set;}}
Where required represents a required field,
The stringlength represents the string length,
RegularExpression represents regular expression validation
Range Validation < Integer, floating point, date >
These 4 verification methods can meet our common validation requirements.
Using regular validation, introduce namespaces:
Using System.ComponentModel.DataAnnotations;
Let's verify that MVC has both client and server-side authentication.
First, we turn off the scripting feature of IE browser.
The menu->internet option opens as shown in the following screen:
Click the "Custom Level ..." button to pop up the following screen:
Locate script, Active Scripting, select Disabled, OK.
Look at us. After disabling the script, the interface has changed because of the script being disabled.
But the server still validates all the data and returns the error message, as shown in:
We can see the process of the client sending the request on the status bar
2, additional validation (server-side JSON validation, comparison validation)
To use additional validation, introduce a namespace:
Using SYSTEM.WEB.MVC
To demonstrate the validation methods for these two extensions, we create a new entity class:
public class staffinfoex{public virtual int Staffinfoexid {get; set;} [Required] Where Staffinfoex is the name of the controller, Checklogid is the authentication method [Remote ("Checklogid", "Staffinfoex", errormessage = "login account is already occupied, please use another account" ] [Display (Name = "login account")] public virtual string Logid {get; set;} [Stringlength (minimumlength = 4, errormessage = "{0} must have a length greater than {2} characters and less than {1} characters")] [Display (Name = "password")] Public virtual string Logpassword {get; set;} [Display (Name = "Confirm password")] [Compare ("Logpassword", errormessage = "Password must be the same")] Public virtual string Logpasswordconfirm {get; set;} [Display (name = "name")] Public virtual string Realname {get; set;}}
Note here to make sure that the controller name and authentication method name of the remote declaration are spelled correctly, otherwise the Create button will not respond.
2.1 Remote, server-side JSON validation
Please modify the URL to: Http://localhost:XXXX/staffinfoex. As declared in the entity class,
We just need to control the class Staffinfoexcontroller by adding the following JSON method to the line:
Verify that the login account is already occupied public Jsonresult Checklogid (string logid) { var result = db. Staffinfoex.count (U = u.logid = = Logid) = = 0; return Json (result, jsonrequestbehavior.allowget); }
When the login account field loses focus, the server-side JSON method is automatically invoked to verify the account usage.
In other words, the remote declaration does not use client-side authentication, but rather the asynchronous server authentication.
Because it is like a login account, you cannot authenticate with the client unless you have all your login accounts
Sent to the client.
2.2 Compare, Comparison verification
Just a simple declaration in the entity class, it is very good to implement the function like password confirmation,
ASP. NET MVC is really too much of a force.
[Display (Name = "Confirm password")] [Compare ("Logpassword", errormessage = "Password must be consistent")] public virtual string Logpasswordconfirm {get; set;}
3, database constraint validation
In addition, we can use a variety of database constraint validation to ensure the validity and integrity of the data.
If you do not want users to use 123456 such an overly simple password, we can use a check constraint
To achieve:
ALTER TABLE staffinfoes with NOCHECK ADD CONSTRAINT Chk_logpasswordcheck (Logpassword not in (' 123 ', ' 123123 ', ' 123456 '))
Where Staffinfoes is the name of the table, Chk_logpassword is the constraint name, and Logpassword is the column name.
Let's start by adding a staffinfo with a password of 123456 and see what happens to our program?
Error message:
The INSERT statement conflicts with the CHECK constraint "Chk_logpassword".
The conflict occurs in the database "bingomvc3dataannotations", table "dbo." Staffinfoes ", column ' Logpassword '.
Statement has been terminated.
Finally, let's summarize the three kinds of data validation methods
1) client script validation, using scripts such as JavaScript for validation, but this validation can be easily masked. But it can
Provide the best user experience.
2) server-side validation, which needs to be sent back to the server for verification, to ensure that data remains in place when the client active script is disabled
Verify. The disadvantage is increased server pressure.
3) database constraint validation, this is a special solution, such as the Web site in the process you can not update the site. All the pressure
are on the database, too many constraints can affect the responsiveness of the site.
In addition, the data validation of ASP. NET can be expanded freely to meet the needs of different situations.
Custom data validation next time.
data validation [source rar download] for the ASP MVC3 Getting Started Guide