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?

2 Answers 2

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..

Sign up to request clarification or add additional context in comments.

1 Comment

I thought I had tried this way as well, but I just changed my code to this and it worked. Thanks!
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

1 Comment

Does FluentValidation also support annotation based validations too? Instead of RuleSet and following expressions?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.