Manually bind JQuery validation after Ajax request

2019-02-14 02:55发布

问题:

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.

回答1:

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



回答2:

var $form = $("form");

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

$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);


回答3:

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



回答4:

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);


回答5:

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.