2013-03-17 41 views
2

我想弄清楚如何驗證用戶在註冊時輸入了匹配的密碼。是否有內置於MVC 4數據註釋的內容,我可以使用它或者是創建自定義驗證屬性的唯一途徑?ASP.NET MVC 4交叉字段或屬性驗證

如果我必須創建一個自定義驗證屬性,我該如何訪問密碼屬性(假設我將註釋放在confirm密碼屬性上)?另外,這種類型的驗證是否有任何常用的庫?

這是我有一個自定義驗證屬性的開始,只是不知道如何訪問密碼屬性:

public class CrossFieldValidationAttribute : ValidationAttribute 
{ 
    public override bool IsValid(object value) //how do I get the other value in here? 
    { 
     //validation logic here 
     return base.IsValid(value); 
    } 
} 

我明白任何幫助!

+0

在創建登錄帳戶時將密碼與數據庫匹配或匹配密碼? (因此註冊)? – bas 2013-03-17 20:03:06

回答

1

您可以創建自己的公共屬性自定義屬性和設置的附加信息。

public class CustomValidationAttribute : ValidationAttribute 
{ 
    public string MeaningfulValidationInfo { get; set; } 

    protected override ValidationResult IsValid(object value, ValidationContext validationContext) 
    { 
     // do whatever meaningful with MeaningfulValidationInfo 
     return base.IsValid(value, validationContext); 
    } 
} 

您可以設定額外的信息是這樣的:

[CustomValidationAttribute(MeaningfulValidationInfo = "blah")] 
public ActionResult Index() 
{ 
    return View(); 
} 

如果你想檢查是否都輸入的密碼是相同的,你可以簡單地驗證您的模型。

public class LoginModel 
    { 
     [Required] 
     [EmailAddress] 
     public string EmailAddress { get; set; } 
     [Required] 
     public string Password { get; set; } 
     [Required] 
     [Compare("Password")] 
     [Display(Name = "Confirm password")] 
     public string ConfirmPassword { get; set; } 
    } 
} 
-2

你可以使用* 比較驗證*控制內置的ASP.NET工具

我在下面提供了一個樣本

<body> 
    <form id="form1" runat="server"> 
    <div> 

    <asp:Label 
     id="lblBirthDate" 
     Text="Birth Date:" 
     AssociatedControlID="txtBirthDate" 
     Runat="server" /> 
    <asp:TextBox 
     id="txtBirthDate" 
     Runat="server" /> 
    <asp:CompareValidator 
     id="cmpBirthDate" 
     Text="(Invalid Date)" 
     ControlToValidate="txtBirthDate" 
     Type="Date" 
     Operator="DataTypeCheck" 
     Runat="server" /> 

    <br /><br /> 

    <asp:Button 
     id="btnSubmit" 
     Text="Submit" 
     Runat="server" /> 

    </div> 
    </form> 
</body> 

請參考任何鏈接的下方擴大你的知識

http://www.java2s.com/Tutorial/ASP.NET/0160__Validation/CompareValidatorperformsthreedifferenttypesofvalidations.htm

http://www.vkinfotek.com/aspnetvalidationcontrols.html

1

比較註釋是最簡單的選擇。如下所示,Compare指向Password屬性。

[Required] 
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)] 
[DataType(DataType.Password)] 
[Display(Name = "Password")] 
public string Password { get; set; } 

[DataType(DataType.Password)] 
[Display(Name = "Confirm password")] 
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] 
public string ConfirmPassword { get; set; }