How to Remote call using bootstrap validator

I only just found out that the bootstrap validation plugins has a validation rule called “remote” which can be used to make an ajax request instead of specifying a custom rule which has an ajax call it in. This will save you heaps of time with those custom validation rules. This is very interesting and simple. You may also like How to jquery validation remote (ajax) using Codeigniter and Form Validation using jQuery and Bootstrap Validator.

bootstrapValidator.js Plugin

<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-validator/0.5.3/js/bootstrapValidator.js"></script>

HTML Code

<form action="" id="defaultForm" enctype="multipart/form-data" method="POST" >
    <div class="row">
        <div class="col-md-12">
            <div class="col-md-6">
                <div class="form-group">
                    <label class="control-label">
                        Email <span class="symbol required"></span>
                    </label>
                    <input type="email" class="form-control" id="email" name="email">
                </div>
            </div>
        </div>
    </div>

    <div class="row col-sm-offset-3">
        <div class="col-sm-4 ">
            <button class="btn btn-dark-blue btn-block " name="submitButton" type="submit">
                <i class="fa fa-save"></i> Save 
            </button>
        </div>
    </div>
</form>

jQuery Code

<script type="text/javascript">
    $(document).ready(function() {
        $('#defaultForm').bootstrapValidator({
            message: 'This value is not valid',
            feedbackIcons: {
                valid: 'glyphicon glyphicon-ok',
                invalid: 'glyphicon glyphicon-remove',
                validating: 'glyphicon glyphicon-refresh'
            },
            fields: {
              
                email: {
                    validators: {
                        notEmpty: {
                            message: 'The driver email is required and cannot be empty'
                        },
                        remote: {
                            url: 'ajax.php',
                            data: function(validator) {
                                return {
                                    email: validator.getFieldElements('email').val()
                                };
                            },
                            message: 'The email address is not available'
                        },
                    }
                },
                
            }
        });
    });
</script>

ajax.php

$query = "select * from users where email  = '".$_POST['email']."' ";
$result  = mysqli_query($con, $query);
if(mysqli_num_rows($result) == 0)
{
    $json['valid'] = true;
}
else
{
    $json['valid'] = false;
}

echo json_encode($json);

Leave a Reply

Your email address will not be published. Required fields are marked *