Email model validation with DataAnnotations and DataType
Asked Answered
S

4

65

I have following model:

public class FormularModel
{
    [Required]
    public string Position { get; set; }
    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }
    [Required]
    public string Webcode { get; set; }
}

Required validation works fine. But when i try with DataType it doesn't react.

Here is my razor code for the email control:

   @Html.TextBoxFor
          (model => model.Email, 
           new { @style = "width: 175px;", @class = "txtField" }
          ) * 

So, anyone know an answer?

TIA

Strip answered 24/1, 2012 at 15:7 Comment(1)
Check this Example: codingfusion.com/Post/…Tenrec
V
150

DataType attribute is used for formatting purposes, not for validation.

I suggest you use ASP.NET MVC 3 Futures for email validation.

Sample code:

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

If you happen to be using .NET Framework 4.5, there's now a built in EmailAddressAttribute that lives in System.ComponentModel.DataAnnotations.EmailAddressAttribute.

Valuable answered 24/1, 2012 at 15:11 Comment(3)
but it accepts 'something@domain' . i guess i will go with regular expression this time.Villegas
As we cant give custom error message. Am using this following way instead. [EmailValidation(ErrorMessage = "The Email Address already exists")] [RegularExpression( "^[a-z0-9_\\+-]+(\\.[a-z0-9_\\+-]+)*@[a-z0-9-]+(\\.[a-z0-9]+)*\\.([a-z]{2,4})$" , ErrorMessage = "Invalid email format." )] [Required(ErrorMessage = "Please enter your e-mail address."), StringLength(50)] public string Email { get; set; }Epithet
That Regex will fail for "ryan.o'[email protected]"Arthro
S
3

I have looked at the source code (reverse engineered by Reflector) and DataType variants are actually not even implemented! (This was for DateType.Date)

So it is not going to work.

I would personally use RegexValidation for email.


For clarity, here is the implementation of IsValid in class DataTypeAttribute:

public override bool IsValid(object value)
{
    return true;
}
Submaxillary answered 24/1, 2012 at 15:9 Comment(2)
hehehe... everything is valid! =)Valuable
Regex validation of email addresses is a really bad idea; the RFC allows to many weird permutations to make a regex feasible. Even tagged emails, as supported by GMail, usually get rejected as invalid, despite being perfectly valid. (davidcel.is/blog/2012/09/06/… points this out well). programmers.stackexchange.com/questions/78353/… explores the various options, but the only 100% guarantee is to email the address and check for bounces.Confectionery
T
3

I used this regex pattern which will allow some of the newer longer extensions (.mynewsite, etc).

@"^[\w-_]+(\.[\w!#$%'*+\/=?\^`{|}]+)*@((([\-\w]+\.)+[a-zA-Z]{2,20})|(([0-9]{1,3}\.){3}[0-9]{1,3}))$"

Not Valid, among others too:

Examples that work:

EDIT - UPDATE 5/17/2024

From a question below, I use this: I'm using an improved regex value, different from the original one above.

using System.ComponentModel.DataAnnotations;



  public static class RegexPatterns
    {
        public const string Email = @"^[a-zA-Z0-9._\\-]+@[a-zA-Z0-9]+(([\\-]*[a-zA-Z0-9]+)*[.][a-zA-Z0-9]+)+(;[ ]*[a-zA-Z0-9._\\-]+@[a-zA-Z0-9]+(([\\-]*[a-zA-Z0-9]+)*[.][a-zA-Z0-9]+)+)*$";
    }
public class User
{
    [Required]
    [RegularExpression(RegexPatterns.Email, ErrorMessage = "Username can only contain alphanumeric characters.")]
    public string Email{ get; set; }

}
Teakwood answered 7/4, 2021 at 15:31 Comment(4)
For those implementing Regex format validations. This can impact the performance of your application.Augury
Can you edit this and show how to implement this regex pattern using DataAnnotations on the original question? I don't know how to add your regex text to DataAnnotations.Ezar
The regex is complicated, so I use a constant. Here's an improved regex: ^[a-zA-Z0-9._\\-]+@[a-zA-Z0-9]+(([\\-]*[a-zA-Z0-9]+)*[.][a-zA-Z0-9]+)+(;[ ]*[a-zA-Z0-9._\\-]+@[a-zA-Z0-9]+(([\\-]*[a-zA-Z0-9]+)*[.][a-zA-Z0-9]+)+)*$ public static class RegexPatterns { public const string Email = @"Add your regex here$"; } public class User { [Required] [RegularExpression(RegexPatterns.Email, ErrorMessage = "Username can only contain alphanumeric characters.")] public string Email { get; set; }Teakwood
@Ezar Look up in my response, I edited it to show how to incorporate this into the class. Hope this helps.Teakwood
A
-6

I think you need to add at html code one componente Html.ValidationMessageFor. This component shows the validation.

The code may be (using razor):

@Html.TextBoxFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)

try it.

Anthrax answered 5/8, 2013 at 21:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.