自定義錯誤訊息

如果你想提供自定義錯誤訊息,你可以這樣做:

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