How to create Ajax request in Bootstrap validator using Laravel validation?

1k views Asked by At

I am creating a form with bootstrap validator. And I am performing a validation using bootstrap validator(client) and laravel validation(server). My problem is I want to perform an ajax request to the laravel to check the username's availability.

In laravel we have this type of validation:

'username'              =>  'required|min:6|max:15|unique:users',

To check the username's availability. Now I want to include this type of checking in the bootstrap validator.

username: {
    validators: {
        notEmpty: {
            message: 'The username is required and cannot be empty'
        },
        stringLength: {
            min: 6,
            max: 15,
            message: 'The username must be more than 6 and less than 15 characters long'
        },
        regexp: {
            regexp: /^[a-zA-Z0-9_\.]+$/,
            message: 'The username can only consist of alphabetica, number, dot and underscore'
        },
        remote: {
            url: '' /*** how can I perform laravel validation with this?
            message: 'The username is not available'
        }
    }
},

How can I do this? Do I need to create a custom helper for this type of checking? Or can I integrate laravel's validation with this?

1

There are 1 answers

0
Jerielle On

Ok I manage to solve it by creating another function within my controller. Here's what I did:

remote: {
    url: "{{ URL::to('/checkUsername') }}",
    data: function(validator) {
        return {
            username: validator.getFieldElements('username').val()
        }
    },
    message: 'The username is not available'
}

In my controller I have this:

public function checkUsernameAvailability() {

    $user = DB::table('authors')->where('username', Input::get('username'))->count();

    if($user > 0) {
        $isAvailable = FALSE;
    } else {
        $isAvailable = TRUE;
    }

    echo json_encode(
            array(
                'valid' => $isAvailable
            ));

}

Then that's it. :)