MVC Validator.TryValidateObject does not validate custom atrribute, validateAllProperties = true
- by nealsu
When calling Validator.TryValidateObject with validateAllProperties = true my custom validation attribute does not get triggered. The ValidationResult does not contain an entry for my erroneous property value. Below is the model, attribute and code used to test this.
//Model
public class Model
{
[AmountGreaterThanZero]
public int? Amount { get; set; }
}
//Attribute
public sealed class AmountGreaterThanZero: ValidationAttribute
{
private const string errorMessage = "Amount should be greater than zero.";
public AmountGreaterThanZero() : base(errorMessage) { }
public override string FormatErrorMessage(string name)
{
return errorMessage;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (value != null)
{
if ((int)value <= 0)
{
var message = FormatErrorMessage(validationContext.DisplayName);
return new ValidationResult(message);
}
}
return null;
}
}
//Validation Code
var container = new Container();
container.ModelList = new List<Model>() { new Model() { Amount = -5 } };
var validationContext = new ValidationContext(container, null, null);
var validationResults = new List<ValidationResult>();
var modelIsValid = Validator.TryValidateObject(container, validationContext, validationResults, true);
Note: That the validation works fine and ValidationResult returns with correct error message if I use the TryValidateProperty method.