自定义错误消息

如果你想提供自定义错误消息,你可以这样做:

public class LoginViewModel
{
    [Required(ErrorMessage = "Please specify an Email Address")]
    [EmailAddress(ErrorMessage = "Please specify a valid Email Address")]
    public string Email { get; set; }
    
    [Required(ErrorMessage = "Type in your password")]
    public string Password { get; set; }
}

当你的错误消息在 ResourceFile(.resx) 中时,你必须指定 ResourceType 和 ResourceName:

public class LoginViewModel
{
    [Required(ErrorMessageResourceType = typeof(ErrorResources), ErrorMessageResourceName = "LoginViewModel_RequiredEmail")]
    [EmailAddress(ErrorMessageResourceType = typeof(ErrorResources), ErrorMessageResourceName = "LoginViewModel_ValidEmail")]
    public string Email { get; set; }
    
    [Required(ErrorMessageResourceType = typeof(ErrorResources), ErrorMessageResourceName = "LoginViewModel_RequiredPassword")]
    public string Password { get; set; }
}