I’m using asp.net mvc 3 with unobtrusive jquery validation. I have a form that is for a model that contains various required attributes and other data annotations.
I am submitting this form using jquery like so
<script type="text/javascript"> $(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
var user = {
UserName: $('#@(Html.IdFor(m => m.UserName))').val(),
Password: $('#@(Html.IdFor(m => m.Password))').val(),
RememberMe: $('#@(Html.IdFor(m => m.RememberMe))').val(),
returnUrl: '@Request.Url.PathAndQuery'
};
$('#loginform').hide();
$('#loading').show();
$.ajax({
url: '@Url.Action("LogOn", "Account")',
type: 'POST',
data: JSON.stringify(user),
dataType: 'json',
processData: false,
contentType: 'application/json;charset=utf-8',
success: function(data) {
if (data.returnUrl) {
window.location.href = data.returnUrl;
} else {
$("#loginform").replaceWith(data);
}
},
error: function(jqXhr, textStatus, errorThrown) {
alert("There was an error logging in :'" + jqXhr.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
},
complete: function() {
$('#loginform').show();
$('#loading').hide();
}
});
});
}); </script>
The problem is that the form is validated (and errors will be shown for required fields etc) and then the form will be submitted which is causing errors.
How do I modify the jquery so that it checks the form is valid before doing this submit?
Turns out a call to if ($(‘form’).valid()) which return true/false if the form is valid