3

I'm trying to validate an email data type in a console app using Data Annotations, but it is returning "true" even though I know for a fact the email address isn't valid (I'm sending in "notavalidemail").

Here is my code.

Model:

class Email
    {
        [DataType(DataType.EmailAddress)]
        public string email { get; set; }
    }

Snippet from Program.cs:

     Email emailAdress = new Email();
     emailAdress.email = "notavalidemail";
     var vc = new ValidationContext(emailAdress, null, null);
     var isValid = Validator.TryValidateObject(emailAdress, vc, null);

Am I missing something, or is it even possible to validate data types this way in a console app?

dkiefer
  • 501
  • 5
  • 13

2 Answers2

4

DataType attributes are used primarily for formatting and not validation, So you have to use [EmailAddress] instead of [DataType(DataType.EmailAddress)]:

public class Email
{
    [EmailAddress]
    public string email { get; set; }
}

Now if you run your application you'll get this validation error:

The email field is not a valid e-mail address.

One more thing: If you need validation for all properties, you have to pass in true for the last parameter of TryValidateObject method:

var isValid = Validator.TryValidateObject(email, context, results, true);

true to validate all properties; if false, only required attributes are validated..

Sirwan Afifi
  • 10,654
  • 14
  • 63
  • 110
  • I thought I had tried this way as well, but I just changed my code to this and it worked. Thanks! – dkiefer Sep 29 '15 at 11:36
2

I think you should use fluent validation instead. Its an easy to use library where u can validate a model and check if the values provided were correct with validate method.

Check the link below:

https://fluentvalidation.codeplex.com/

The example below may some what help you with this!

http://www.codeproject.com/Articles/326647/FluentValidation-and-Unity

Check this answer too

https://stackoverflow.com/a/6807706/2191018

Community
  • 1
  • 1
Amey Khadatkar
  • 414
  • 3
  • 16
  • Does FluentValidation also support annotation based validations too? Instead of RuleSet and following expressions? – hina10531 Dec 04 '17 at 22:59