ASP.NET MVC 5: EmailAddress attribute custom error message

こ雲淡風輕ζ 提交于 2019-12-24 07:41:33

问题


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


来源:https://stackoverflow.com/questions/41890299/asp-net-mvc-5-emailaddress-attribute-custom-error-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!