Search code examples
javascripttwitter-bootstrap-3bootstrapvalidatorjqbootstrapvalidationbootstrapvalidator-1000hz

How to dynamically pass an id to url of Bootstrap validator rule: remote for a same form input field?


Bootstrap Validator v 0.5.2 is being re-used for validating form (#myForm) in a modal. Need is dynamically pass an unique id (Foreign Key) to 'url' of 'remote' rule when form loads on a modal as below.

var remoteUrl = "/remoteurl/";
var id = <Foreign key of the record>

$('#myForm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        fieldName: {
            validators: {
                remote: {
                    url: remoteUrl + id, //dynamically passing id. // but not passing dynamically.
                    type: 'POST',
                    message: "This is the message!"
                }
            }
        } 
    }
});

Issue:
On modal loading, 'id' passes successfully into form dynamically. Though, 'bootstrapValidator' gets the very first passed 'id' into the form, unless page reloads.


Solution

  • Found a solution!

    Add a hidden input field for add the foreign key.

    <input type="hidden" value="" name="foreignKey" id="foreignId">
    

    And, dynamically pass foreign key to this field.

    $('#foreignId').val(id);
    

    Then, as follow

    fieldName: {
        validators: {
            remote: {
                url: remoteUrl,
                 data: function(validator, $field, value) {
                    return {
                        foreignKey: validator.getFieldElements('foreignKey').val()
                    };
                },
                type: 'POST',
                message: "This is the message!"
            }
        }
    }
    

    Now, it works for me. 'Id' is dynamically pass for remote method.