Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC 5: EmailAddress attribute custom error message

In register form I use EmailAddress attribute to validate user email.

public class RegisterViewModel
{
    [Required(ErrorMessage = "Pole wymagane")]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    [EmailAddress]
    public string Email { get; set; }
}

Is there any chance to show what is wrong with email address if validation fails? For example 'oops, I see that your email address contains whitespace'

like image 857
mateusz-dot Avatar asked Aug 31 '25 10:08

mateusz-dot


2 Answers

You have to add another validation for that. Example using [RegularExpression]

public class RegisterViewModel
{
    [Required(ErrorMessage = "Pole wymagane")]
    [RegularExpression(@"^\S*$", ErrorMessage = "Email Address cannot have white spaces")]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    [EmailAddress]
    public string Email { get; set; }
}
like image 175
prtdomingo Avatar answered Sep 03 '25 19:09

prtdomingo


You can define your own regular expression for email:

// built-in [EmailAddress] does not allow white spaces around email
public const string EmailValidationRegEx = @"^\s*\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*\s*$"; 

Note: I have just added white spaces around the existing .NET regex pattern for email match: "^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$"

Now you can use this new regex pattern instead of [EmailAddress] attribute:

public class RegisterViewModel
{
    private string _email;

    [Required(ErrorMessage = "Pole wymagane")]
    [Display(Name = "Email")]
    [DataType(DataType.EmailAddress)]
    [RegularExpressionWithOptions(EmailValidationRegEx, ErrorMessage = "Invalid email")]
    public string Email 
    { 
        get => _email;

        set
        {
            _email = string.IsNullOrEmpty(value) ? string.Empty : value.Trim();
        }
    }
}

Note that I have modified the setter to trim() the value. This ensures that we always get rid of extra white spaces before using the email value.

like image 30
Hooman Bahreini Avatar answered Sep 03 '25 21:09

Hooman Bahreini