Reputation: 28545
Hi I am using some ajax with jquery to perform a post of a form.
Heres my jquery:
$("#submit").click(function (e) {
e.preventDefault();
$.post("Account/LogOn",
$(this.form).serialize(),
function (data) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error").replaceWith(data.error);
}
},
'json'
);
return false;
});
This works as expected, however the in built MVC validation no longer works? (the error messages dont show username required/password required if they are omitted and the form is submitted.).
Any Ideas why clientside validation no longer works?
thanks
Upvotes: 2
Views: 1181
Reputation: 5018
Because the client side validation is triggered by form posts and you are no longer posting the form, you are performing a jQuery post which essentially circumvents the validation triggers. You have to manually trigger the validation in your javascript and than check if the client-side validation found any errors, and if it did not than you can proceed with the ajax post.
Edit: Here's the documentation for how to do that. The code will look similar to this....
$("#submit").click(function (e) {
e.preventDefault();
$(this.form).validate();
if($(this.form).valid())
{
$.post("Account/LogOn",
$(this.form).serialize(),
function (data) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error").replaceWith(data.error);
}
},
'json'
);
return false;
}
});
Upvotes: 2