需要MVC条件验证

时间:2012-03-25 02:14:33

标签: asp.net-mvc

我正在使用自定义验证,它适用于一个值,但我需要检查多个值,例如:

  

[RequiredIf(“Country”,“Canada”,“Postal Code is required”)]
  [RequiredIf(“Country”,“United States”,“Zip Code is required”)]
  public string PostalCode {get;组; }

我得到Duplicate'RequireIf'属性! 提前谢谢。

1 个答案:

答案 0 :(得分:3)

您不能将相同的数据注释两次应用于一个属性。

我不知道您当前的RequiredIfAttribute代码是什么样的,但我认为您必须编写另一个自定义验证程序来检查所选国家/地区并相应地调整错误消息。

public class PostalCodeRequiredAttribute : ValidationAttribute
{
    private const string errorMessage = "{0} is required.";
    public string CountryPropertyName { get; private set; }

    public PostalCodeRequiredAttribute(string countryPropertyName) : base(errorMessage)
    {
        CountryPropertyName = countryPropertyName;
    }

    public override string FormatErrorMessage(string name)
    {
        return string.Format(errorMessage, name);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null) return ValidationResult.Success;

        var countryPropertyInfo = validationContext.ObjectType.GetProperty(CountryPropertyName);
        string country = countryPropertyInfo.GetValue(validationContext.ObjectInstance, null).ToString();
        // assuming your country property is bound to a string

        string name;

        if (country == "United States")
             name = "Zip code";
        else if (country == "Canada")
             name = "Postal code";
        else
             return ValidationResult.Success;
             // assuming postal code not required for all other countries

        return new ValidationResult(FormatErrorMessage(name));
    }
}

假设您的国家/地区属性名为Country

,您可以这样注释
[PostalCodeRequired("Country")]
public string PostalCode { get; set; }