条件范围验证器+ MVC

时间:2013-07-18 10:38:09

标签: asp.net-mvc validation asp.net-mvc-4 model data-annotations

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

这样的东西
public bool retired {get, set};

[RangeIf("retired",20,50)]
public int retirementAge {get, set};

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您需要创建自定义验证属性,如下所示:

public class RangeIfAttribute : ValidationAttribute
{
    protected RangeAttribute _innerAttribute;

    public string DependentProperty { get; set; }

    public RangeIfAttribute(string dependentProperty, int minimum, int maximum)
    {
        _innerAttribute = new RangeAttribute(minimum, maximum);
        DependentProperty = dependentProperty;
    }

    public RangeIfAttribute(string dependentProperty, double minimum, double maximum)
    {
        _innerAttribute = new RangeAttribute(minimum, maximum);
        DependentProperty = dependentProperty;
    }

    public RangeIfAttribute(string dependentProperty, Type type, string minimum, string maximum)
    {
        _innerAttribute = new RangeAttribute(type, minimum, maximum);
        DependentProperty = dependentProperty;
    }

    public override string FormatErrorMessage(string name)
    {
        return _innerAttribute.FormatErrorMessage(name);
    }

    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        // get a reference to the property this validation depends upon
        var containerType = validationContext.ObjectInstance.GetType();
        var field = containerType.GetProperty(DependentProperty);

        if (field != null && field.PropertyType.Equals(typeof(bool)))
        {
            // get the value of the dependent property                
            var dependentValue = (bool)(field.GetValue(validationContext.ObjectInstance, null));

            // if dependentValue is true...
            if (dependentValue)
            {
                if (!_innerAttribute.IsValid(value))
                    // validation failed - return an error
                    return new ValidationResult(FormatErrorMessage(validationContext.DisplayName), new[] { validationContext.MemberName });
            }
        }

        return ValidationResult.Success;
    }
}

然后,您可以像在问题中一样在模型中使用它。