Reputation: 1546
In a model of my ASP.NET MVC application I would like validate a textbox as required only if a specific checkbox is checked.
Something like
public bool retired {get, set};
[RangeIf("retired",20,50)]
public int retirementAge {get, set};
How can I do that?
Upvotes: 1
Views: 643
Reputation: 9155
You need to create your custom validation attribute like this:
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;
}
}
Then, you can use it in your Model just like in your question.
Upvotes: 1