I have a form that is using the jQuery validate functionality, with some custom functions validating the values with ajax posts.
My problem is when I submit the form, I have the submitHandler do ajax post to check if the field is valid by checking in the DB. I only want the form to submit if the value returned is valid.
(function ( $ ) {
$.fn.checkValidSubDomain = function (params) {
params['siteID'] = wlSiteID;
var deferred = $.Deferred();
var promise = deferred.promise();
$("div#"+$(this).attr('id')+"Info").html(copyItems["info_checkingStatus"]);
var jqxhr = $(this).ajaxPost('checkValidSubDomain', params)
jqxhr.success(function (data){
if (data.validSubdomain) {
$("div#"+$(this).attr('id')+"Info").html(copyItems["info_"+$(this).attr('id')+"Available"]);
deferred.resolve(data);
} else {
$("div#"+$(this).attr('id')+"Info").html(copyItems["err_"+$(this).attr('id')+"Unavailable"]);
deferred.reject(jqxhr, 'error');
}
})
jqxhr.error(function (jqXHR, status, error){
$("div#"+$(this).attr('id')+"Info").html(copyItems["err_"+$(this).attr('id')+"Unavailable"]);
deferred.reject(jqXHR, status, error);
});
return promise;
};
})(jQuery);
var validationRules = {
submitHandler: function(form) {
var promise;
if ($('input[name="domainSetting"]:checked').val() == 'subDomain') {
alert("checking subdomain - " + $('#subDomainSiteName').val())
promise = $('#subDomainSiteName').checkValidSubDomain({'subDomain': $('#subDomainSiteName').val(), 'domain':$("#domainSelect option:selected").val()});
}
promise.done(function() {
form.submit();
});
return false;
},
onfocusout: false,
onkeyup: false,
rules: {
subDomainSiteName: {
required: {
depends: '#domainSettingSubDomain:checked'
}
}
}
};
$('#domainSettingsFRM').formValidation(validationRules);
I'm not sure how I get to the form to only submit if the field is valid. Currently, it's just showing the alert and then submitting the form regardless of the value.
Any help appreciated
EDIT
I think I just figured it out. Once the async ajax call is finished, the promise.done() will trigger. At that point I simply check the state to see if it is resolved or rejected. Changing the code to the following seems to do the trick.
promise.done(function() {
if (promise.state() == "resolved") {
form.submit();
}
});