Examples of Asp. Mvc 2.0 user server verification (4) and asp. mvc instances
This section describes how to use ASP. net mvc 2.0 Server-side verification. As you know, it is insecure to use only JS client for verification in a project. Users can disable JS to bypass client verification, So server-side verification is required.
For server-side verification, we mainly call the class libraries in the System. ComponentModel. DataAnnotations namespace.
Let's take the registration page as an example to explain the server verification, mainly to complete the following verification on the registration page
1. the user name cannot be blank
2. The password cannot be blank, and the password length cannot be less than 5 digits,
3. The password must be the same as the password.
4. the email format must be correct.
Let's take a look.
All fields in MVC can be verified by setting verification rules at the MODEL layer.
1. User Name Verification
To verify the user name, you only need to verify that the user name is not empty.Required attributes, Bind this attribute to the username field of the MODEL.
/// <Summary> /// username /// </summary> [DisplayName ("username")] [Required (ErrorMessage = "username cannot be blank! ")] Public string UserName {get; set ;}
The parameters in Required indicate the specific prompt information. If the user name is blank, a prompt indicating that the user name cannot be blank will appear on the ASPX page at the front end. Of course, an error message should be displayed on the front-end. Use the <%: Html. ValidationMessageFor (m => m. UserName) %> flag to display the error message on the foreground.
2. Password Verification
Password verification includes the password cannot be blank or the password length limit.
If the verification password is empty, use the Required attribute.
Use the StringLength attribute to verify the password length.
/// <Summary> /// password /// </summary> [DisplayName ("password")] [Required (ErrorMessage = "password cannot be blank")] [StringLength (10, ErrorMessage = "password length cannot be less than 5 characters", MinimumLength = 5)] public string UserPwd {get; set ;}
StringLengthThe first parameter indicates the maximum length of the password, and ErrorMessage indicates the error message when the conditions are not met.
MinimumLength indicates the minimum length of the input content.
Of course, the front-end must have an error message. The error message is as follows:
<%: Html. ValidationMessageFor (m => m. UserPwd) %>
3. Verify that the password is consistent with the password
To verify that the password is the same as to confirm whether the password is the same, this is a little complicated and requires custom verification rules. For custom verification rules, we need to inherit the ValidationAttribute class and then implement its isvaild method.
/// <Summary> /// this custom class is used to verify the password and confirm that the password must be consistent /// </summary> [AttributeUsage (AttributeTargets. class, AllowMultiple = true, Inherited = true)] public class PwdMatch: ValidationAttribute {private object _ typeid = new object (); public string PWD {get; set ;} // password public string ConfirmPwd {get; set;} // Confirm Password public PwdMatch (string pwd, string confirmPwd): base () {PWD = pwd; ConfirmPwd = confirmPwd ;} /// <Summary> /// error message returned /// </summary> /// <param name = "name"> </param> /// <returns> </ returns> public override string FormatErrorMessage (string name) {return ErrorMessage;} // <summary> // rewrite TYPEID // </summary> public override object TypeId {get {return _ typeid ;}} /// <summary> /// determine whether to think of it. /// </summary> /// <param name = "value"> the value of value is actually the MODEL class submitted by the MODEL. </param> /// <returns> </returns> publ Ic override bool IsValid (object value) {PropertyDescriptorCollection properties = TypeDescriptor. getProperties (value); object originalValue = properties. find (PWD, true ). getValue (value); // get the password object confirmValue = properties. find (ConfirmPwd, true ). getValue (value); // get the value of the Confirm Password return Object. equals (originalValue, confirmValue) ;}} after the PwdMatch attribute class is created, you can mark it on the registered MODEL and submit the registration, [PwdMatch ("UserPwd ", "ConfirPwd", ErrorMessage = "¨ ¹ code? And®? Are you sure you want to recognize? No?? ")] Public class RegisterModel {}
The password in the first parameter table of PwdMatch is the same as the Password attribute in RegisterModel, and the second field is the confirmation password. The name is the same as the confirmation Password attribute in RegisterModel, the last parameter is the error message.
Of course, the error message should also be displayed on the front-end, using <%: Html. ValidationSummary (true, "Use®? User Accounts have been created for ä ää § loss ° loss of ownership and defeat! ") %> A list of general error messages is displayed on the foreground.
4. Email Verification
Email verification is mainly about email format verification. Whether the verification format meets the requirements. You can use the RegularExpressions attribute to verify your email.
/// <Summary> /// user email /// </summary> [DisplayName ("Mailbox")] // [DataType (DataType. emailAddress)] [RegularExpression (@ "^ \ w + (-\ w +) | (\. \ w +) * \ @ [A-Za-z0-9] + ((\. |-) [A-Za-z0-9] + )*\. [A-Za-z0-9] + $ ", ErrorMessage =" Email format error ")] public string Email {get; set ;}
The first parameter is the regular expression for mailbox verification, and the second parameter is the error message.
The error message <%: Html. ValidationMessageFor (m => m. Email) %> is displayed on the ASPX page.
The above is the verification of user registration information. Of course, when submitting information, we need to determine whether the verification is successful. We use ModelState. isValid is used to determine whether the verification is successful. TRUE indicates that the verification is passed, and FALSE indicates that the verification is not passed.
Model Code:
/// <Summary> /// register the user MODEL /// </summary> [PwdMatch ("UserPwd", "ConfirPwd ", errorMessage = "password does not match confirm")] public class RegisterModel {// <summary> // username // </summary> [DisplayName ("username")] [Required (ErrorMessage = "the user name cannot be blank! ")] Public string UserName {get; set ;}/// <summary> /// password /// </summary> [DisplayName (" password ")] [Required (ErrorMessage = "password cannot be blank")] [StringLength (10, ErrorMessage = "password length cannot be less than 5 characters", MinimumLength = 5)] public string UserPwd {get; set;} [DisplayName ("Confirm Password")] [Required (ErrorMessage = "Confirm Password cannot be blank! ")] [StringLength (10, ErrorMessage =" Make sure the password length cannot be less than 5 characters ", MinimumLength = 5)] public string ConfirPwd {get; set ;} /// <summary> /// user email /// </summary> [DisplayName ("Mailbox")] // [DataType (DataType. emailAddress)] [RegularExpression (@ "^ \ w + (-\ w +) | (\. \ w +) * \ @ [A-Za-z0-9] + ((\. |-) [A-Za-z0-9] + )*\. [A-Za-z0-9] + $ ", ErrorMessage =" Email format error ")] public string Email {get; set ;}} /// <summary> /// this custom class is used to verify the password and confirm that the password must be consistent /// </summary> [AttributeUsage (AttributeTargets. class, AllowMultiple = true, Inherited = true)] public class PwdMatch: ValidationAttribute {private object _ typeid = new object (); public string PWD {get; set ;} // password public string ConfirmPwd {get; set;} // Confirm Password public PwdMatch (string pwd, string confirmPwd): base () {PWD = pwd; ConfirmPwd = confirmPwd ;} /// <summary> /// error message returned // </summary> /// <param name = "name"> </param> // <returns> </returns> public override string FormatErrorMessage (string name) {return ErrorMessage;} // <summary> // rewrite TYPEID // </summary> public override object TypeId {get {return _ typeid ;}} /// <summary> /// determine whether to think of it. /// </summary> /// <param name = "value"> the value of value is actually the MODEL class submitted by the MODEL. </param> /// <returns> </returns> public override bool IsValid (object value) {PropertyDescriptorCollection properties = TypeDescriptor. getProperties (value); object originalValue = properties. find (PWD, true ). getValue (value); // get the password object confirmValue = properties. find (ConfirmPwd, true ). getValue (value); // get the value of the Confirm Password return Object. equals (originalValue, confirmValue );}}
Front-end Page code
<% @ Page Language = "C #" Inherits = "System. Web. Mvc. ViewPage <MvcLogin. Models. RegisterModel>" %> <! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN "" http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <Html xmlns =" http://www.w3.org/1999/xhtml "> <Head runat =" server "> <title> registration page </title> <script type =" text/javascript "src = ".. /.. /Scripts/jquery-1.4.1-vsdoc.js "> </script> <script type =" text/javascript "src = ".. /.. /Scripts/jquery. validate. js "> </script> <script type =" text/javascript "> // $ (). ready (function () {// $ ("# form1 "). validate (// {// rules: // {// UserName: // {// required: true //}, // UserPwd: // {// required: true, // minleng Th: 6 //}, // ConfirPwd: // {// required: true, // minlength: 6, // failed to: "# UserPwd "//}, // Email: // {// email: true //}, // messages: // {// UserName: // {// required: "<span style = 'color: red'> the user name cannot be blank! </Span> "//}, // UserPwd: // {// required:" <span style = 'color: red'> the password cannot be blank! </Span> ", // minlength: jQuery. format (" <span style = 'color: red'> the password length cannot be less than {0} characters! </Span> ") //}, // ConfirPwd: // {// required:" <span style = 'color: red'> confirm that the password cannot be blank! <Span> ", // minlength: jQuery. format (" confirm that the password length cannot be less than {0} characters! "), // Failed to:" <span style = 'color: red'> the two passwords are inconsistent! </Span> "//}, // Email: // {// email:" <span style = 'color: red'> Incorrect Email format! </Span> "//}, // onkeyup: false //});//}); </script>
Controller code
/// <Summary> /// submit registration /// </summary> /// <param name = "model"> </param> /// <returns> </returns> [HttpPost] public ActionResult Register (Models. registerModel model) {if (ModelState. isValid) {// bool result = false; if (! New Models. sqlHelper (). existUser (model) {result = new Models. sqlHelper (). addUser (model);} if (result) {// The page is FormsService. signIn (model. userName, false); return RedirectToAction ("index");} else {// return to the registration page ViewData ["msg"] = "failed to add a user "; return View (model) ;}} else {// Verification Failed // return to the registration page ViewData ["msg"] = "failed to add a user "; return View (model );}}
The above is the whole process of implementing the Asp. Mvc 2.0 user server verification instance. I hope you can combine the previous client verification to practice. I hope this article will help you better master the Asp. Mvc 2.0 verification function.