簡體   English   中英

使用DataAnnotations比較兩個模型屬性

[英]Using DataAnnotations to compare two model properties

如何編寫比較兩個字段的自定義ValidationAttribute? 這是常見的“輸入密碼”,“確認密碼”方案。 我需要確保兩個字段相等並保持一致,我想通過DataAnnotations實現驗證。

因此,在偽代碼中,我正在尋找一種實現類似以下內容的方法:

public class SignUpModel
{
    [Required]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Required]
    [Display(Name = "Re-type Password")]
    [Compare(CompareField = Password, ErrorMessage = "Passwords do not match")]
    public string PasswordConfirm { get; set; }
}

public class CompareAttribute : ValidationAttribute
{
    public CompareAttribute(object propertyToCompare)
    {
        // ??
    }

    public override bool IsValid(object value)
    {
        // ??
    }
}

所以問題是,我該如何編碼[Compare] ValidationAttribute?

確保您的項目引用了system.web.mvc v3.xxxxx。

然后您的代碼應該是這樣的:

using System.Web.Mvc;

[Required(ErrorMessage = "This field is required.")]    
public string NewPassword { get; set; }

[Required(ErrorMessage = "This field is required.")]
[Compare(nameof(NewPassword), ErrorMessage = "Passwords don't match.")]
public string RepeatPassword { get; set; }

在ASP.NET MVC 3框架中有一個CompareAttribute可以做到這一點。 如果您正在使用ASP.NET MVC 2並以.Net 4.0為目標,則可以查看ASP.NET MVC 3源代碼中的實現。

這是達林答案的較長版本:

public class CustomAttribute : ValidationAttribute
{    
    public override bool IsValid(object value)
    {
        if (value.GetType() == typeof(Foo))
        {
           Foo bar = (Foo)value;
           //compare the properties and return the result
        }

        throw new InvalidOperationException("This attribute is only valid for Foo objects");
    }
}

和用法:

[MetadataType(typeof(FooMD))]
public partial class Foo
{
     ... functions ...
}

[Custom]
public class FooMD
{
     ... other data annotations ...
}

該錯誤將顯示在@Html.ValidationSummary(false)

您可以具有一個自定義的驗證屬性,並將其應用於模型而不是單個屬性。 這是一個示例,您可以看一下。

如果你們正在使用MVC 4,請嘗試以下代碼..它將解決您的錯誤..

請使一個Metadataclass比在部分類中實現comfirmemail屬性更好。 檢查下面的代碼以獲取更多詳細信息。

using System;
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    using StringlenghtMVC.Comman;
    using System.Web.Mvc;

using System.Collections;

    [MetadataType(typeof(EmployeeMetaData))] //here we call metadeta class
    public partial class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
        public Nullable<int> Age { get; set; }
        public string Gender { get; set; }
        public Nullable<System.DateTime> HireDate { get; set; }

       //[CompareAttribute("Email")]
        public string ConfirmEmail { get; set; }
    }

    public class EmployeeMetaData
    {
        [StringLength(10, MinimumLength = 5)]
        [Required]
        //[RegularExpression(@"(([A-za-Z]+[\s]{1}[A-za-z]+))$", ErrorMessage = "Please enter Valid Name")]
        public string Name { get; set; }

        [Range(1, 100)]
        public int Age { get; set; }
        [CurrentDate]
        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
        public DateTime HireDate { get; set; }

        //[RegularExpression(@"^[\w-\._\%]+@(?:[\w]{2,6}$")]
        public string Email { get; set; }

        [System.Web.Mvc.CompareAttribute("Email")]
        public string ConfirmEmail { get; set; }


    }

對於將來遇到此問題的人們,我試圖編寫一個驗證屬性,如果對象的屬性為某個值,該屬性將評估正則表達式。 就我而言,如果地址是送貨地址,則我不希望啟用郵政信箱,因此我想出了以下方法:

用法

[Required]
public EAddressType addressType { get; set; } //Evaluate Validation attribute against this

[EvaluateRegexIfPropEqualsValue(Constants.NOT_PO_BOX_REGEX, "addressType", EAddressType.Shipping, ErrorMessage = "Unable to ship to PO Boxes or APO addresses")]
public String addressLine1 { get; set; }

這是驗證屬性的代碼:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EvaluateRegexIfPropEqualsValue : ValidationAttribute
{
    Regex _regex;
    string _prop;
    object _targetValue;

    public EvaluateRegexIfPropEqualsValue(string regex, string prop, object value)
    {
        this._regex = new Regex(regex);
        this._prop = prop;
        this._targetValue = value;
    }

    bool PropertyContainsValue(Object obj)
    {
        var propertyInfo = obj.GetType().GetProperty(this._prop);
        return (propertyInfo != null && this._targetValue.Equals(propertyInfo.GetValue(obj, null)));
    }

    protected override ValidationResult IsValid(object value, ValidationContext obj)
    {
        if (this.PropertyContainsValue(obj.ObjectInstance) && value != null && !this._regex.IsMatch(value.ToString()))
        {
            return new ValidationResult(this.ErrorMessage);
        }
        return ValidationResult.Success;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM