【问题标题】:MVC Conditional Vallidation RequiredIf需要 MVC 条件验证如果
【发布时间】:2012-03-25 02:14:33
【问题描述】:

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

[RequiredIf("国家", "加拿大", "邮政编码为必填项") ]
[RequiredIf("Country", "United States", "Zip Code is required")]
公共字符串 PostalCode { 获取;放; }

我得到重复的“RequiredIf”属性! 提前致谢。

【问题讨论】:

  • 只是为了澄清 - 您希望错误消息根据选择的国家/地区而有所不同?
  • 构建项目时出现重复错误。是的,我想收到取决于国家/地区的错误消息。谢谢

标签: asp.net-mvc


【解决方案1】:

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

我不知道您当前的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; }

【讨论】:

  • 非常感谢,可惜没用,这里是国家属性 [必填] public string Country { get;放; }。您是正确的邮政编码并非所有其他国家/地区都需要。
  • 什么具体不起作用?是否存在编译时错误或未按预期验证?此代码仅用于服务器端验证。
  • 我创建了一个新的简单项目并添加了您的模型,效果很好;我认为问题出在我原来的项目上。非常感谢。
  • 问题与 Javascript 和 Telerik ScriptRegistrar 有关。再次感谢
  • 没问题。很高兴你把事情解决了。
猜你喜欢
  • 1970-01-01
  • 2014-05-09
  • 2016-05-17
  • 1970-01-01
  • 2011-01-25
  • 1970-01-01
  • 1970-01-01
  • 2017-08-13
  • 2018-03-20
相关资源
最近更新 更多