我需要在验证程序发现错误时更改字段样式。在我看来,我已经做到了
<form action="@Url.Action("Editar")" method="post" name="fCadastro" id="fCadastro" class="stdform" role="form">
<p>
<label>Nome:</label>
<span class="field field-validation-error">
<input type="text" name="Nome" id="nome" class="form-control" value="@Model.Nome" maxlength="50" />
@Html.ValidationMessageFor(model => model.Nome)
</span>
<small class="desc">Informe o nome do produto. Tamanho máximo: 50 caracateres</small>
</p>
</form>
@section scripts{
<script src="~/Scripts/jquery.validate.js" defer></script>
<script src="~/Scripts/jquery.validate.additional.methods.min.js" defer></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js" defer></script>
}
我的ViewModel类有:
[Required(ErrorMessage = "Campo obrigatório")]
public string Nome { get; set; }
我已使用以下命令配置web.config:
<appSettings>
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
因此,我需要应用错误样式并将焦点设置为具有错误的字段,而不仅仅显示错误消息。我已经尝试过的一个解决方案是覆盖Unobtrusive的errorPlacement功能:
settings.errorPlacement = function (label, element) {
// Call old handler so it can update the HTML
oldErrorPlacement(label, element);
form.addClass('has-error');
element.parents('span').addClass('text-danger');
element.focus();
};
但没有成功。