如何覆盖无效的电子邮件验证消息mvc 5

时间:2016-09-17 09:38:41

标签: asp.net-mvc validation email

我正在尝试覆盖模型验证错误消息中的默认无效邮件消息

[EmailAddress(ErrorMessageResourceName = "Email", ErrorMessageResourceType = typeof(Resources.Validation))]

和资源文本:"{0}" is not a valid e-mail address

我希望它看起来像:"[the input email]" is not valid email adress

但我明白了:"Email" is not a valid email address

我能以某种方式通过模型验证消息吗?

编辑:

我设法简化了一点但仍然需要帮助

[EmailAddress(ErrorMessage = string.Format(Resources.Validation.Validation.Email, ?what to put here?))]

1 个答案:

答案 0 :(得分:0)

您可以创建验证属性

这是一个例子,

我创建了一个名为EmailAttribute的类,该类继承了ValidationAttribute

 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (value != null)
        {
            string email = value.ToString();

            if (Regex.IsMatch(email, @"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}", RegexOptions.IgnoreCase)) // If it is a email address.
            {
                return ValidationResult.Success; // Success
            }
            else
            {
                return new ValidationResult(email + " is not a Valid Email.");// here is the trick.
            }
        }
        else
        {
            return new ValidationResult("" + validationContext.DisplayName + " is required"); // required message.
        }
    }

在模型中,您可以使用它。

[Email]
public string Mail { get; set; }

<强>结果

enter image description here

希望有所帮助,