Manually bind JQuery validation after Ajax request

2019-02-14 02:23发布

I'm requesting an ASP.net MVC view into a live box and the view contains form fields that have been marked up with attributes to be used by JQuery's unobtrusive validators plug-in.

The client script is not however working and my theory is that its because the validation framework is only being triggered on page load which has long since passed by the time the MVC view has been loaded into the live box.

Thus how can I let the validation framework know that it has new form fields to fix up?

Cheers, Ian.

5条回答
Deceive 欺骗
2楼-- · 2019-02-14 02:42

You may take a look at the following blog post. And here's another one.

查看更多
孤傲高冷的网名
3楼-- · 2019-02-14 02:45

For some reason I had to combine bjan and dfortun's answers...

So I put this in my view:

@{
  this.ViewContext.FormContext = new FormContext();
}

And this execute this after the ajax call finishes:

var form = $("#EnrollmentForm");
form.unbind();
form.data("validator", null);
$.validator.unobtrusive.parse(document);
form.validate(form.data("unobtrusiveValidation").options);
查看更多
可以哭但决不认输i
4楼-- · 2019-02-14 02:52
var $form = $("form");

$form.unbind();
$form.data("validator", null);

$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
查看更多
做自己的国王
5楼-- · 2019-02-14 03:00

I had a similar issue. I had a form that was using Ajax requests to re-display a part of the form with different form fields. I used unobtrusive validation by manually doing it on the client side using the

@Html.TextBoxFor

for my text boxes. For some reason the validation works when attempting to submit with invalid fields (i.e., the text boxes get outlined in red and the appropriate error messages display with the content I put in the

data_val_required

attribute, for example.

However, after I click a button that makes an Ajax request to modify the form with different fields and then submit again, only the red outline on the invalid fields display, but no error messages are rendered.

bjan's trick worked for me, but I still can't see what was causing the issue. All the HTML necessary to carry out the client-side validation was there I just can't figure out why the error message attribute values wouldn't display.

All I can think of is that the jQuery validation code doesn't make a second attempt to check the form fields after a submit was made.

查看更多
手持菜刀,她持情操
6楼-- · 2019-02-14 03:03

Another option, rather trick, which worked for me. Just add following line in the beginning of the partial view which is being returned by ajax call

this.ViewContext.FormContext = new FormContext(); 

Reference

查看更多
登录 后发表回答