Search code examples
jqueryajaxjquery-validation-engine

jQuery validationEngine Ajax validation for form fields needs callback


If you are using jQuery ValidationEngine to validate a form with AJAX you direct handling of the before and after with callbacks:

jQuery("#testForm").validationEngine('attach', 
{
    promptPosition : "bottomLeft", 
    validationEventTrigger : "submit", 
    ajaxFormValidation: true,
    onBeforeAjaxFormValidation: function() {
        alert('before');
    },
    onAjaxFormComplete : function(status, form, errors, options) {
        alert('after');
    }
});

That's cool and all, but I just want to validate an individual field (in this case, the text input "input[name='name']"):

<script>
$("#testBtn").click(function() {
    var resp = $("#testForm").validationEngine("validate");
});
</script>
<form onsubmit="return false;" 
    onclick="$('#testForm').validationEngine('hide')" 
    name="testForm" 
    id="testForm" 
    action="" method="POST">
    <input type="hidden" name="providerId" value="0" />
    <input name="name" value="Default Provider" class="validate[required, ajax[checkProviderNameExists]]" />
    <button id="testBtn">Submit</button>
</form>

When the submit button is clicked, jQuery ValidationEngine will submit the checkProviderNameExists request to the server and display the correct/incorrect prompt depending on the result. If validation passes, however, I want to be able to submit the form at that point. Is this possible? Basically I need a callback function for field validation so I can take appropriate action depending on if the form validates or not.

For the sake of completeness here is my implemenation of the custom ajax validator:

"checkProviderNameExists" : {
    "url": "/settings/checkprovidernameexists",
    "extraDataDynamic": "providerId",
    "alertText": "* This provider name already exists",
    "alertTextLoad": "Checking name..."
}

Solution

  • Setting an AJAX validator on an individual field only executes at runtime. To accomplish what I wanted, I had to use ajax to validate the entire form, and in that particular ajax handler do validation on the individual fields.