Form Validation all form input fields using ajax json and remote server

July 21, 2017

Whilst working on our latest project I came across a great jquery validation script called FormValidation. Excellent documentation and examples.

 

http://formvalidation.io

 

I couldn't find the exact use in the examples so I had to do a bit of JavaScript coding.

 

I wanted to get the validation on all the form fields and have it do a remote ajax call to do the actual validation at the server side, I wanted to do this to make use of laravel's validation functionality. Also it needed to be in real time so as the user was typing it was validating. This is what I came up with :)

 

 

$(document).ready(function() {

 

    var inputs = {

        framework: 'bootstrap',

        icon: {

            valid: 'glyphicon glyphicon-ok',

            invalid: 'glyphicon glyphicon-remove',

            validating: 'glyphicon glyphicon-refresh'

        },

        fields: {}

    };

 

    $('#form_id *').filter(':input').map(function(i,el) {

        var $el = $(el);

        var $id = $el.attr('id');

        if( !$el.val() || $id !== null || $id !== undefined) {

            inputs.fields[$id] = {

                verbose: false,

                validators: {

                    notEmpty: {

                        message: 'The field is required'

                    },

                    remote: {

                        url: '/validator/',

                        type: 'POST',

                        name: $id,

                        delay: 1000     // Send Ajax request every 2 seconds

                    }

                }

            };

        }

    }).get();

 

    $('#form_id').formValidation(inputs);

 

});

 

https://laravel.com/docs/master/validation

Share on Facebook
Share on Twitter
Please reload

Recent Posts