user125264 user125264 - 5 months ago 19
jQuery Question

how to get current field name in jquery.validate() remote class rule

I am trying to restructure the data that is sent via jquery.validate() remote when adding a classRule.

jQuery.validator.addClassRules("remote-validation", {
required: true,
remote: {
url : '/!/check/?ajax=true',
type:'post',
data: { table : $('body').attr('data-app'), id: $('input[name=id]').val(), field: $(this).val() }
}
});


just trying to extract the field name that is being used to make it easier to process server side, but cant seem to find out how to extract the current field that is being validated.

my goal is to have the following generated

{ table : 'companies', id: '123', field: 'companyName }


Any suggestions greatly appreciated

Answer

I can't find it documented anywhere, but I think you can specify a function for the parameter value for a rule, and if you do, the element will be passed as the first (and only parameter) when that function is called.

If this is true, you could try the following:

jQuery.validator.addClassRules("remote-validation", {
    required: true,
    remote: function(element) {
        return {
            url : '/!/check/?ajax=true',
            type:'post',
            data: {
                table: $('body').attr('data-app'),
                id: $('input[name=id]').val(),
                field: $(element).val()
            }               
        }
    }
});

This jsfiddle shows it working. In the fiddle, click the "submit" button, then start typing in the first input. For each keystroke an ajax call will be made.