The custom validation attribute always returns IsValid == true

I am trying to get a simple custom validation attribute but can't see what I don't see.

[AttributeUsage(AttributeTargets.Property)]
public class CustomValAttribute :ValidationAttribute
{
    public override bool IsValid(object value)
    {
        return false;
    }
}

public class TestModel
{
   [CustomVal]
   public string Name { get; set; }
}

Then I try to check:

var test = new TestModel (){ Name = "test" };
 ValidationContext contx = new ValidationContext(test, null, null);
 var results = new List<ValidationResult>();
 Console.WriteLine(Validator.TryValidateObject(test, contx, results));

But the result is always true, then I found that my custom validation method is IsValidnever called Validator. What am I doing wrong?

+4
source share
1 answer

Using

Validator.TryValidateObject(test, contx, results, true);

If the last parameter is not set to true, Validatorchecks properties only with RequiredAttribute(and checks only this attribute, ignoring other attributes).

+6
source

Source: https://habr.com/ru/post/1533638/


All Articles