ASP.NET MVC5客户端验证

时间:2016-09-02 23:14:23

标签: javascript jquery asp.net-mvc validation asp.net-mvc-5

如果选中复选框,我在视图中有一个金额字段。

Razor一旦使用模型数据呈现视图,用户就会选中一个没有输入相应金额的复选框。出现验证消息。如果我取消选中该复选框,则验证消息不会消失。

我尝试使用jquery删除生成的所有规则,但如果用户再次复选,则在回发之前,这些验证规则将被删除(除非我存储它们...这真的是真的难看。)

是否有一种可接受的方法可以在MVC模型中使用相同的要求重新验证客户端?

型号:

[Display(Name = "Include Amount")]
public bool IncludeAmount { get; set; }
[Display(Name = "Amount")]
[RequiredIf("IncludeAmount", TargetValue = true, ErrorMessage = "Amount is required.")]
[MaxDigits(10, 2)]
[RegularExpression(RegularExpressions.Money, ErrorMessage = ErrorMessages.NumericValueInvalidFormat)]
[GreaterThanZero]
public Nullable<decimal> Amount { get; set; }

查看:

<td class="dataEntryLabel" colspan="2">
    @Html.LabelFor(model => model.IncludeAmount)
</td>
<td class="dataEntryField" colspan="2">
    @Html.CheckBoxFor(model => model.IncludeAmount, new { id = "IncludeAmount" })
    <span class="dollar-sign">@Html.TextBoxFor(model => model.Amount, "{0:F}", new { id = "Amount", disabled = "disabled" })</span>
    @Html.ValidationMessageFor(model => model.Amount)
</td>

JavaScript(客户端):

function fixUnobtrusiveValidations() {
    var form = getForm();
    (<any>$).validator.unobtrusive.parse(form);
}

function onClickCheckBoxIncludeAmount(){
        fixUnobtrusiveValidations();
}

$('IncludeAmount').click(onClickCheckBoxIncludeAmount);

2 个答案:

答案 0 :(得分:0)

尝试此操作以禁用onclick事件的客户端验证 请参阅:https://jqueryvalidation.org/validate/#onclick

$("#myform").validate({
    onclick: false,
});

OR

$("#yourChkboxID").validate({
    onclick: false,
});

答案 1 :(得分:0)

这有效:

if (!($('#IncludeAmount').checked)){
   toggleValidatorVisibility($('#Amount'), false);
}

function toggleValidatorVisibility(element: any, value) {
  var td: any = element.closest('td');
  if (value) {
       td.find('span.field-validation-error').show();
  } else {
       td.find('span.field-validation-error').empty();
  }
}