1

I have tried to follow guidelines found by Googling for validating email addresses, and used the following:

    [Required(ErrorMessage = "Email required.")]
    [ValidateEmail(ErrorMessage = "Valid email required.")]
    public string Email { get; set; }

And this is the attribute class:

public class ValidateEmailAttribute : RegularExpressionAttribute
{
    public ValidateEmailAttribute() :  
        base(@"^(([A-Za-z0-9]+_+)|([A-Za-z0-9]+\-+)|([A-Za-z0-9]+\.+)|([A-Za-z0-9]+\++))*[A-Za-z0-9]+@((\w+\-+)|(\w+\.))*\w{1,63}\.[a-zA-Z]{2,6}$") {}  
} 

Also found Googling for examples.

However, I tried this version of an email attribute and another one, but neither stops me from entering whatever in the email field. I tried just entering a simple name, with spaces and all, and it went through just fine!

Why isn't it kicking in and stopping this? The Required attribute works, it's just the regex one that doesn't.

Anders
  • 12,556
  • 24
  • 104
  • 151

3 Answers3

2

Please note that this kind of email validation covers just a small portion of the IETF standards and should not be used in production code. It does not account, first of all, for the length of the local part (can be any number here), nor it allows quoted words and it not even allows non-ASCII characters.

I suggest you to take a look at EmailVerify.NET, a Microsoft .NET component that can validate the syntax of email addresses according to all of the current IETF standards (and can even contact the related mail exchangers to check if their mailboxes exist or not). As you might expect, this component can be easily integrated with the DataAnnotation framework too.

Disclaimer: I am the lead developer for this product.

Efran Cobisi
  • 6,138
  • 22
  • 22
1

Found the answer myself, the custom attribute had to have an "adapter" registered for it. Here's the solution for anyone else who might need it:

How to create custom validation attribute for MVC

Community
  • 1
  • 1
Anders
  • 12,556
  • 24
  • 104
  • 151
0

Are you checking if your model is valid in your controller?

[HttpPost]
public ActionResult Register(User user)
{
    if (Model.IsValid())
    {
        // process model
        return View("Success");
    }

    return View(user);
}

And are you referencing the MicrosoftAjax and MicrosoftMvcValidation scripts and validating your model at the top of your view?

<script src="/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="/Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>

<% Html.EnableClientValidation(); %>

See http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx for a more detailed description.

shuniar
  • 2,592
  • 6
  • 31
  • 38