The custom ValidationAttribute does not work. Always returns true

I created a custom ValidationAttribute class to validate the age of a person in my application:

public class MinimumAgeAttribute : ValidationAttribute
{
    public int MinAge { get; set; }

    public override bool IsValid(object value)
    {
        return CalculateAge((DateTime) value) >= MinAge;
    }

    private int CalculateAge(DateTime dateofBirth)
    {
        DateTime today = DateTime.Now;
        int age = today.Year - dateofBirth.Year;
        if (dateofBirth > today.AddYears(-age)) age--;
        return age;
    }
}

      

Data annotations are set in the field as follows:

[MinimumAge(MinAge = 18, ErrorMessage = "Person must be over the age of 18")]   
public DateTime DateOfBirth;

      

The binding in my UI is set like this:

<DatePicker SelectedDate="{Binding SelectedPerson.DateOfBirth, UpdateSourceTrigger=PropertyChanged, ValidatesOnDataErrors=True}" Grid.Column="1"/>

      

When I set the date (for example) to 09/06/2007, for example, it Validator.TryValidateObject

always returns true.

Why? This only affects my custom classes, all of which are contained in System.ComponentModel.DataAnnotations work fine.

+3


source to share


1 answer


The reason your custom ValidationAttribute isn't working is because WPF doesn't (by default) look at such classes when doing validation. The default authentication mechanism implements the IDataErrorInfo interfaces (available for .NET 4.0 and earlier) or INotifyDataErrorInfo (introduced in .NET 4.5). If you don't want to implement any of these interfaces then you can create a ValidationRule, but I prefer to use the interfaces mentioned above.

You can find many examples of how to do this online, but for a quick search, this is a blog post (which was a quick scan that I felt was very thorough).




EDIT

Since you seem to be more interested in using Data Annotations instead of IDataErrorInfo / INotifyDataErrorInfo or Validation Rule interfaces, I think the Microsoft TechNet article "Validating Data in MVVM" is a very simple and thorough implementation of using data annotations for validation. I have read this solution myself and have recommended it to others.

0


source







All Articles