DataAnnotationsExtensions的自定义错误消息

时间:2013-08-08 09:29:10

标签: validation asp.net-mvc-4 data-annotations

我正在努力让Scott Kirkland的DataAnnotationsExtensions与我的MVC4项目一起工作。但我遇到了客户端验证电子邮件地址的问题。我添加了一个带有错误消息的EmailAddress注释,但是当我输入无效的电子邮件地址时,我没有收到自定义错误消息,而是收到通用电子邮件错误消息“请输入有效的RecipientEmail地址。”。

我的班级看起来像这样:

public class NpRequest
{
    [DisplayName("Telefonnummer som skal overdrages")]
    [Required(ErrorMessage = "Angiv telefonnummeret som skal overdrages")]
    public string PhoneNumer { get; set; }

    [DisplayName("Recipient email address")]
    [EmailAddress(ErrorMessage = "This is my custom error message")]
    [Required(ErrorMessage = "The recipient email address is required")]
    public string RecipientEmail { get; set; }
    public RecipientTypeEnum RecipientType { get; set; }
}

我的观点:

--- SNIPPET BEGIN ---

    <div class="editor-label">
        @Html.LabelFor(model => model.PhoneNumer)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.PhoneNumer)
        @Html.ValidationMessageFor(model => model.PhoneNumer)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.RecipientEmail)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.RecipientEmail)
        @Html.ValidationMessageFor(model => model.RecipientEmail)
    </div>

    <p>
        <input type="submit" value="Create" />
    </p>

--- SNIPPET END ---

编辑: 当我检查HTML时,它看起来像这样:

<input class="text-box single-line input-validation-error" data-val="true" data-val-email="This is my custom error message" data-val-required="The recipient email address is required" id="RecipientEmail" name="RecipientEmail" type="email" value="">

似乎我的自定义错误消息被放入data-val-email属性中。我的印象是DataAnnotationExtension自动将我的自定义错误消息添加到ModelState,从而也将其添加到field-validation-error span,这显示了MVC验证错误。

这个假设是错的吗?我应该编写自己的javascript,它会提取自定义错误消息属性并将其注入字段验证错误范围吗?

谁能看到我做错了什么?

1 个答案:

答案 0 :(得分:0)

我最终使用了System.ComponentModel.DataAnnotations和DataAnnotationsExtensions的混合。我发现大多数时候数据注释也会进行客户端验证。唯一没有客户端验证的时间是我检查电话号码是否正确长度。

public class NpRequest
{
    [DisplayName("Phone number")]
    [MinLengthAttribute(8, ErrorMessage = "Phone number must be 8 digits")]
    [MaxLengthAttribute(8, ErrorMessage = "Phone number must be 8 digits")]
    [DigitsAttribute(ErrorMessage = "Phone number must be 8 digits")]
    [Required(ErrorMessage = "Phone number is required")]
    public string PhoneNumber { get; set; }

    [DisplayName("Modtagers email adresse")]
    [EmailAddressAttribute(ErrorMessage = "Invalid email")]
    [Required(ErrorMessage = "Email is required")]
    public string RecipientEmail { get; set; }
    public RecipientTypeEnum RecipientType { get; set; }
}