asp.net-mvc - 依赖于另一个字段的属性

标签 asp.net-mvc validation model annotations

在我的 ASP.NET MVC 应用程序模型中,我希望仅在选中特定复选框时才根据需要验证文本框。

就像是

public bool retired {get, set};

[RequiredIf("retired",true)]
public string retirementAge {get, set};

我怎样才能做到这一点?

谢谢你。

最佳答案

看看这个:http://blogs.msdn.com/b/simonince/archive/2010/06/04/conditional-validation-in-mvc.aspx

我对代码进行了一些修改以满足我的需要。也许您也从这些变化中受益。

public class RequiredIfAttribute : ValidationAttribute
{
    private RequiredAttribute innerAttribute = new RequiredAttribute();
    public string DependentUpon { get; set; }
    public object Value { get; set; }

    public RequiredIfAttribute(string dependentUpon, object value)
    {
        this.DependentUpon = dependentUpon;
        this.Value = value;
    }

    public RequiredIfAttribute(string dependentUpon)
    {
        this.DependentUpon = dependentUpon;
        this.Value = null;
    }

    public override bool IsValid(object value)
    {
        return innerAttribute.IsValid(value);
    }
}

public class RequiredIfValidator : DataAnnotationsModelValidator<RequiredIfAttribute>
{
    public RequiredIfValidator(ModelMetadata metadata, ControllerContext context, RequiredIfAttribute attribute)
        : base(metadata, context, attribute)
    { }

    public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
    {
        // no client validation - I might well blog about this soon!
        return base.GetClientValidationRules();
    }

    public override IEnumerable<ModelValidationResult> Validate(object container)
    {
        // get a reference to the property this validation depends upon
        var field = Metadata.ContainerType.GetProperty(Attribute.DependentUpon);

        if (field != null)
        {
            // get the value of the dependent property
            var value = field.GetValue(container, null);

            // compare the value against the target value
            if ((value != null && Attribute.Value == null) || (value != null && value.Equals(Attribute.Value)))
            {
                // match => means we should try validating this field
                if (!Attribute.IsValid(Metadata.Model))
                    // validation failed - return an error
                    yield return new ModelValidationResult { Message = ErrorMessage };
            }
        }
    }
}

然后使用它:
public DateTime? DeptDateTime { get; set; }
[RequiredIf("DeptDateTime")]
public string DeptAirline { get; set; }

关于asp.net-mvc - 依赖于另一个字段的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3713281/

相关文章:

javascript - 当您的应用程序使用客户端和服务器端 mvc 框架时,如何处理路由?

像 b-0212 这样的字符串的 Javascript 验证

php - 动态 W3C 验证

asp.net-mvc - ASP.net MVC - 使用没有查询字符串值或花哨路由的模型绑定(bind)器

ruby-on-rails - rails : how do I use question marks in a model?

asp.net-mvc - 我可以在 Owin 中使用两种身份验证方法吗?

asp.net-mvc - 在哪里可以存储 ASP.NET MVC 应用程序的源代码副本?

java - Model 类和 DAO 类的区别

c# - 使用局部 View 的 MVC 4 验证

C# "validate"绑定(bind)到表单的对象的最佳方法