简体   繁体   中英

Custom ValidationAttribute doesn't work. Always returns true

I've created a custom ValidationAttribute class to check 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;
    }
}

The data annotation is set on the field like this:

[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, Validator.TryValidateObject always returns true.

Why? This only seems to affect my custom classes, all the ones provided in System.ComponentModel.DataAnnotations work fine.

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

You can find a lot of examples on how to do this online, but doing a quick search found this blog post (which on a quick scan I felt was very thorough).


EDIT

Since you seemed more keen on using Data Annotations instead of IDataErrorInfo/INotifyDataErrorInfo interfaces or Validation Rule, I think the Microsoft TechNet article "Data Validation in MVVM" is a very clean and thorough implementation of using Data Annotations for validation. I read through the solution myself and would recommend it to others.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM