ASP.MVC 2.0 User Server Authentication example explanation (4) _ Practical Skills

Source: Internet
Author: User

This section explains the use of server-side validation for ASP.net MVC 2.0. You know, a project only with JS client authentication is not safe, users can disable JS to bypass client authentication, so must have server-side validation.
About server-side validation, the main call to the class library inside the System.ComponentModel.DataAnnotations namespace.
This time we still take the registration page as an example to explain server-side validation, mainly on the registration page to complete the following verification
1. User name cannot be empty
2. Password can not be null, password length can not be less than 5 digits,
3. Password and Confirm password input must be the same
4. Message format must be correct
Let's look at the effect chart first.

The validation of all the fields in MVC actually requires only the validation rules to be set at the model level.
1. User name Verification
for User name verification, only need to verify that the username is not empty, use the Required property , bind this property to the model's user name section on it.

<summary> 
  ///username 
  ///</summary> 
  [DisplayName ("User name")] 
  [Required (errormessage=] User name cannot be empty! ")] 
  public string UserName 
  {get; set;} 

The parameters inside the required indicate a specific hint, and if the user name is empty, a prompt appears in the foreground ASPX page that the username cannot be empty. Of course, the error message will be displayed in the foreground. Use the <%: html.validationmessagefor (m=>m.username)%> tag to display the wrong message in the foreground

2. Password Verification
Password Authentication includes password cannot be null and password length limit.
Use the Required property to verify that the password is empty and that the user name is null.
Verify the length of the password using the Stringlength property.

<summary> 
  ///password 
  ///</summary> 
  [DisplayName ("password")] 
  [Required (errormessage=) Password cannot be empty "] 
  [stringlength (errormessage =" Password length cannot be less than 5 bits, minimumlength=5)]] public 
  string Userpwd 
  { Get 
   ; 
   Set 
  

The first parameter of the

stringlength represents the maximum length of the password, errormessage the error message indicating that the condition is not satisfied. The
Minimumlength represents the minimum length of the input content.
Of course, the front desk must have a place to display the error message and display the error message we use the following
<% : html.validationmessagefor (m=>m.userpwd )%>

3. Verify that the password and Confirm password are consistent
to verify the password and confirm that the password is consistent, this is a little more complicated and requires our custom validation rules. Custom validation rules We need to inherit the Validationattribute class. Then implement its Isvaild method.

<summary>///This custom class is used to validate passwords and confirm passwords must be consistent///</summary> [AttributeUsage (AttributeTargets.Class, Allowmult Iple = 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>///Returns the error message///</summary>///<param name= "name" ></param>/// 
  <returns></returns> public override string Formaterrormessage (string name) {return errormessage; 
    ///<summary>///overrides typeid///</summary> public override object typeID {get { 
   return _typeid; }///<summary>///determine if the value of the///</summary>///<param name= "value" >value is actually model submitted Model class </param>///<returns></returns> public override bool IsValid (object value) {PropertyDescriptorCollection properties = T 
   Ypedescriptor.getproperties (value); Object OriginalValue = Properties. Find (PWD, true). GetValue (value);//Get Password Object Confirmvalue = properties. Find (Confirmpwd, true). 
 
  GetValue (value);//Get the value of the confirmation password return object.equals (OriginalValue, Confirmvalue); Pwdmatch attribute class is created, it can be marked on the registration model above, and then submitted to register, it will be validated [Pwdmatch ("Userpwd", "confirpwd", errormessage = "Secret ¨¹ code? ¨¡¤
 ? No, a £¤ match? ")]

 public class Registermodel {}

Pwdmatch the password on the first parameter table, the name is the same as the password property in Registermodel, the second field is the confirmation password, the name and Registermodel are the same as the confirmation password property, and the last parameter is the error message.
Of course, also want to display the error message in the foreground, use <%:html.validationsummary (True, "use the ® ¡ì Create Ä¡ä build ¡§ lost º¡ì defeat 㨹!") %> can display a general list of error messages in the foreground.

4. Mailbox Verification
Mailbox authentication is primarily a mailbox format verification, verifying that the format meets the requirements. Verify mailboxes We can use the RegularExpressions property.

<summary> 
  ///user mailbox 
  ///</summary> 
  [DisplayName ("Mailbox")] 
  //[datatype ( datatype.emailaddress)] 
  [RegularExpression (@ "^\w+ (-\w+) | ( \.\w+)) *\@[a-za-z0-9]+ (\.| -) [a-za-z0-9]+) *\. [a-za-z0-9]+$ ", errormessage =" e-mail format error ")] public 
  string Email 
  {get 
   ; 
   Set 
  


The first parameter mailbox verifies the regular expression, and the second parameter is the error message.
Error messages are displayed in the ASPX page with <%:html.validationmessagefor (m=>m.email)%>
The above is the user registration information verification, of course, when we submit the information, to determine whether the validation is passed, we use Modelstate.isvalid to determine whether the validation pass, true means pass, false means failed.
Model Code:

<summary>///Registered user model///</summary> [Pwdmatch ("Userpwd", "confirpwd", errormessage = "Password and confirmation mismatch") ] public class Registermodel {///<summary>///user name///</summary> [DisplayName ("User name")] [R 
  Equired (errormessage= "User name cannot be empty!")] 
 
  public string UserName {get; set;} <summary>///password///</summary> [DisplayName ("password")] [Required (errormessage= "Password cannot be empty")] [stri 
   Nglength (errormessage = "Password length cannot be less than 5 bits, minimumlength=5)]" public string userpwd {get; 
  Set 
  [DisplayName ("Confirm password")] [Required (errormessage= "Confirm password cannot be blank!")] 
   [stringlength = errormessage = "Confirm password length cannot be less than 5 bits, minimumlength=5)]" public string confirpwd {get; 
  Set  
  ///<summary>///User mailbox///</summary> [DisplayName ("Mailbox")]//[datatype (datatype.emailaddress)] [RegularExpression (-\w+) | (^\w+) | ( \.\w+)) *\@[a-za-z0-9]+ (\.| -) [a-za-z0-9]+) *\. 
 [a-za-z0-9]+$ ", errormessage =" e-mail format error ")] public string Email {get; 
  Set }///<summary>///This custom class is used to validate passwords and confirm passwords must be consistent///</summary> [AttributeUsage (AttributeTargets . class, AllowMultiple = True, inherited = True]] public class Pwdmatch:validationattribute {private Object _type 
  id = 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>///Returns the error message///</summary>///<param name= "name" ></param>/// 
  <returns></returns> public override string Formaterrormessage (string name) {return errormessage; 
    ///<summary>///overrides typeid///</summary> public override object typeID {get { 
   return _typeid; }///<summary>///Determine if you think of///</summary>///<param name= "VAlue ">value's value is actually model-submitted model class </param>///<returns></returns> public override bool IsValid (ob 
   Ject value) {PropertyDescriptorCollection properties = typedescriptor.getproperties (value); Object OriginalValue = Properties. Find (PWD, true). GetValue (value);//Get Password Object Confirmvalue = properties. Find (Confirmpwd, true). 
 
  GetValue (value);//Get the value of the confirmation password return object.equals (OriginalValue, Confirmvalue);  } 
 }

foreground 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  
 ">  

Controller code

<summary> 
 ///Registration submission 
 ///</summary> 
 ///<param name= "model" ></param> 
 /// <returns></returns> 
 [HttpPost] public 
 actionresult Register (Models.registermodel model) 
 { 
  if (modelstate.isvalid) 
  { 
   //verify through 
   bool result = false; 
   if (!new models.sqlhelper (). Existuser (model)) 
   {result 
    = new Models.sqlhelper (). AddUser (model); 
   } 
 
   if (result) 
   { 
    //Add successfully to the homepage 
    formsservice.signin (model. UserName, false); 
    Return redirecttoaction ("index"); 
   } 
   else 
   { 
    //Return to the registration page 
    viewdata["msg"] = "Add user failed"; 
    return View (model); 
   } 
  else 
  { 
   //verify does not pass 
   //Return to the registration page 
   viewdata["msg"] = "Add user failed"; 
   return View (model); 
  } 
 

The above is ASP.MVC 2.0 user server Verification example of the implementation of the whole process, I hope you can combine a client verification practice, I hope this article can better help you master ASP.MVC 2.0 authentication function.

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.