2013-07-18 118 views
0

在我的ASP.NET MVC應用程序的模型中,我希望只有在選中特定複選框時才按需要驗證文本框。有條件的範圍驗證器+ MVC

喜歡的東西

public bool retired {get, set}; 

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

我怎麼能這樣做?

回答

0

您需要創建自定義的驗證屬性是這樣的:

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

然後,你可以用它在你的模型,就像在你的問題。