1

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

就像是

public bool retired {get, set};

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

我怎样才能做到这一点?

4

1 回答 1

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;
    }
}

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

于 2013-07-18T18:09:24.597 回答