2

I am using MVC3 and in certain locations in the code I am using the System.ComponentModel.DataAnnotations.DataType.EmailAddress attribute and letting MVCs Model validation do the validation for me.

However, I would now like to validate an email address in a different section of code where I am not using a model. I would like to use the same method that is already being used by MVC, however I was unable to find any information on how to do so.

EDIT - Sorry if my question was unclear. I will attempt to clarify.

Here is a snippet from the RegisterModel that is included with the default MVC template:

    public class RegisterModel
    {
...

        [Required]
        [DataType(DataType.EmailAddress)]
        [DisplayName("Email address")]
        public string Email { get; set; }
...
     }

These attributes instruct mvcs model validation on how to validate this model.

However, I have a string that should contain an email address. I would like to validate the email address the same way that mvc is doing it.

string email = "noone@nowhere.com";
bool isValid = SomeMethodForValidatingTheEmailAddressTheSameWayMVCDoes(email);
BigJoe714
  • 6,732
  • 7
  • 46
  • 50

3 Answers3

5

As others have said, the DataType attribute doesn't actually do any validation. I would recommend you to look at Data Annotations Extensions which includes already written validation extensions for a variety of things, including Email.

It is also possible to do model validation on your full model explicitly: Manual Validation with Data Annotations.

If you want to do per attribute validation for a specific field/property, you can also look at the tests for DataAnnotationExtensions which should give you what you want:

[TestMethod]
public void IsValidTests()
{
    var attribute = new EmailAttribute();
    Assert.IsTrue(attribute.IsValid(null)); // Don't check for required
    Assert.IsTrue(attribute.IsValid("foo@bar.com"));
    ..
}
Can Gencer
  • 8,822
  • 5
  • 33
  • 52
0

Have a look at this blog post by Scott Guthrie, which shows how to implement validation of an email address using a custom attribute (based on the RegularExpressionAttribute).

You can reuse that logic if you need to validate the email address somewhere else.

M4N
  • 94,805
  • 45
  • 217
  • 260
0

You may want to look at this question: Is the DataTypeAttribute validation working in MVC2?

To summarize, [DataType(DataType.EmailAddress)] doesn't actually validate anything, it just says "hey, this property is supposed to be an e-mail address". Methods like Html.DisplayFor() will check for this and render it as <a href="mailto:foo">foo</a>, but the IsValid() method is pretty much a simple return true;.

You'll have to roll your own code to actually perform validation. The question linked above has some sample code you can use as a starting point.

Community
  • 1
  • 1
Brant Bobby
  • 14,956
  • 14
  • 78
  • 115