Search code examples
c#exceptionannotations

C# DataAnnotation doesn't throw exception when data is invalid?


I've got a very quick code definition using Data:

using System.ComponentModel.DataAnnotations;
class UseDataAnnotations
{
    [Required(ErrorMessage = "Name is compulsory")]
    [StringLength(20)]
    [RegularExpression(@"^[A-Z]{5, 20}$")]
    public string Name { get; set; }
}
class Program
{
    public static void Main(String [] args)
    { 
        UseDataAnnotations obj = new UseDataAnnotations();
        obj.Name = null;
        var context = new ValidationContext(obj, null, null);
        var result = new List<ValidationResult>();
        bool IsValid = Validator.TryValidateObject(
            obj, 
            context,
            null, 
            true);
        Console.WriteLine(IsValid);
        foreach(var x in result)
        {
            Console.WriteLine(x.ErrorMessage);
        }
    }
}

I would expect: as long as "Name" field is null, all the checks should fail and throw some kind of exception.

But on running this program, it just prints "False" nothing else happened. So where did I get wrong, did my "DataAnnotation" worked at all?

I'm using vs2017. Thanks a lot.


Solution

  • The validation works fine and you can get the false as expected but, you are not passing the result on the TryValidateObject method to fill it up with the errors. For sample:

    UseDataAnnotations obj = new UseDataAnnotations();
    obj.Name = null;
    
    var context = new ValidationContext(obj, null, null);
    var result = new List<ValidationResult>();
    
    // pass the result here as the argument to fill it up with the erros.
    bool IsValid = Validator.TryValidateObject(obj, context, result, true);
    
    Console.WriteLine(IsValid);
    
    foreach(var x in result)
    {
        Console.WriteLine(x.ErrorMessage);
    }
    

    See the working sample here: https://dotnetfiddle.net/lI3z1M