Search code examples
c#validationattributessystem.componentmodel

Validation doesn't fire (System.ComponentModel.DataAnnotations)


I have this class here with 2 properties Name and Age

using System.ComponentModel.DataAnnotations;
public class Person
{
    [Required(AllowEmptyStrings = false)]
    [StringLength(25, MinimumLength = 2)]
    [RegularExpression(@"^[a-zA-Z]+$")]
    public string Name { get; set; }
    [Range(0, 100)]
    public int Age { get; set; }
}

and I try to validate the values

Person pTemp = new Person();
pTemp.Name = "x"; //invalid because length <2
pTemp.Age = 200; //invalid because > 100
//validation here 
var context = new ValidationContext(pTemp);
var results = new List<ValidationResult>();
var isValid = Validator.TryValidateObject(pTemp, context, results);
results.ForEach(x => Console.WriteLine(x.ErrorMessage));

but the only validation attribute that fires is the [Required]

where is my mistake?


Solution

  • Use another overload:

    var isValid = Validator.TryValidateObject(pTemp, context, results, true);

    From MSDN:

    public static bool TryValidateObject(
       Object instance,
       ValidationContext validationContext,
       ICollection<ValidationResult> validationResults,
       bool validateAllProperties
    )
    

    validateAllProperties Type: System.Boolean true to validate all properties; if false, only required attributes are validated..

    Since bool is equal to false by default you have validated only Required properties.