I have a value on my model, that must fall within the range of two other values on my model.
For example:
public class RangeValidationSampleModel
{
custom validation attributes are indeed a good thought. something like (digging up some snippet o'mine found who knows where a while ago):
public sealed class MustBeGreaterThan : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' must be greater than '{1}'";
private string _basePropertyName;
public MustBeGreaterThan(string basePropertyName)
: base(_defaultErrorMessage)
{
_basePropertyName = basePropertyName;
}
//Override default FormatErrorMessage Method
public override string FormatErrorMessage(string name)
{
return string.Format(_defaultErrorMessage, name, _basePropertyName);
}
//Override IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
var lowerBound = (int)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
var thisValue = (int)value;
if (thisValue < lowerBound)
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
//value validated
return null;
}
}
public sealed class MustBeLowerThan : ValidationAttribute
{
private const string _defaultErrorMessage = "'{0}' must be lower than '{1}'";
private string _basePropertyName;
public MustBeLowerThan(string basePropertyName)
: base(_defaultErrorMessage)
{
_basePropertyName = basePropertyName;
}
//Override default FormatErrorMessage Method
public override string FormatErrorMessage(string name)
{
return string.Format(_defaultErrorMessage, name, _basePropertyName);
}
//Override IsValid
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var basePropertyInfo = validationContext.ObjectType.GetProperty(_basePropertyName);
var upperBound = (int)basePropertyInfo.GetValue(validationContext.ObjectInstance, null);
var thisValue = (int)value;
if (thisValue > upperBound)
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
//value validated
return null;
}
}
then decorate your class
public class RangeValidationSampleModel
{
[MustBeGreaterThan("MinValue")]
[MustBeLowerThan("MaxValue")]
int Value { get; set; }
int MinValue { get; set; }
int MaxValue { get; set; }
}
and you should be good to go