Passing custom parameters to ValidationAttribute
Like this?
public class StringLengthValidatorNullable : ValidationAttribute
{
public int MinStringLength { get; set; }
public int MaxStringLength { get; set; }
public override bool IsValid(object value)
{
if (value == null)
{
return false;
}
var length = value.ToString().Length;
if (length < MinStringLength || length >= MaxStringLength)
{
return false;
}
return true;
}
}
Use:
[StringLengthValidatorNullable(MinStringLength = 1, MaxStringLength = 16)]
public string Name {get; set;}
You could also pass parameters that are other properties in the same model.
Create a custom validation attribute:
public class SomeValidationAttribute : ValidationAttribute
{
//A property to hold the name of the one you're going to use.
public string OtherProperty { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//Get the value of the property using reflection.
var otherProperty = validationContext.ObjectType.GetProperty(OtherProperty);
var otherPropertyValue = (bool)otherProperty.GetValue(validationContext.ObjectInstance, null);
if (value != null && otherPropertyValue)
{
return ValidationResult.Success;
}
return new ValidationResult("Invalid property message.");
}
}
Then pass the name of the property you're going to use.
public class RequestModel
{
public bool SomeProperty { get; set; }
[SomeValidation(OtherProperty = "SomeProperty")]
public DateTime? StartDate { get; set; }
}