Custom ValidationAttribute doesn't work. Always returns true

六月ゝ 毕业季﹏ 提交于 2019-12-07 13:42:09

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/30720865/custom-validationattribute-doesnt-work-always-returns-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!