MVC4 ValidationMessageFor

时间:2013-02-04 00:12:36

标签: c# jquery .net asp.net-mvc-4 html-helper

我有一个视图,它使用ValidationMessageFor访问模型中包含的数据注释,并且没有任何问题。但是,除了显示相关控件之外的验证消息(作为标准实践),我想在用户将鼠标悬停在验证警告图标上时显示验证消息。

我已经设法使这部分工作,但它要求有问题的控件在用户点击验证警告图标之前有焦点,否则它什么都不显示。是否可以通过jQuery检索验证消息?

型号:

[Required(ErrorMessageResourceName = "EmailRequiredErrorMessage", ErrorMessageResourceType = typeof(Resources.Languages.Models.RegistrationValidateModel))]
[StringLength(60, ErrorMessageResourceName = "EmailStringLengthErrorMessage", ErrorMessageResourceType = typeof(Resources.Languages.Models.RegistrationValidateModel))]
[Display(Name = "EmailDisplayName", ResourceType = typeof(Resources.Languages.Models.RegistrationValidateModel))]
[RegularExpression(@".+@.+\..+", ErrorMessageResourceName = "EmailInvalidRegularExpressionErrorMessage", ErrorMessageResourceType = typeof(Resources.Languages.Models.RegistrationValidateModel))]
public string Email { get; set; }

查看

@Html.ValidationMessageFor(m => m.Email)

生成的HTML

<input class="span12" data-val="true" data-val-length="You must enter an email address less than 60 characters long" data-val-length-max="60" data-val-regex="You must enter a valid email address" data-val-regex-pattern=".+@.+\..+" data-val-required="You must enter an email address1" id="Email" name="Email" type="text" value="" />

...

<span class="field-validation-valid" data-valmsg-for="Email" data-valmsg-replace="true"></span>

目前,在验证后,悬停无法检索错误消息

enter image description here

但是,如果您给出控件焦点,然后单击验证警告图标,则会显示该消息(尽管位置略有不同):

enter image description here

1 个答案:

答案 0 :(得分:1)

使用jQuery访问该属性应该没有问题,无论控件是否具有焦点。尝试

$("#Email").attr("data-val-required")