MVC Validator.TryValidateObject does not validate custom atrribute, validateAllProperties = true

Posted by nealsu on Stack Overflow See other posts from Stack Overflow or by nealsu
Published on 2013-06-24T16:18:31Z Indexed on 2013/06/24 16:21 UTC
Read the original article Hit count: 182

Filed under:
|
|

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.

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about mvc