ASP.NET MVC 5: EmailAddress attribute custom error

2019-07-25 17:37发布

问题:

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'

回答1:

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; }
}