简体   繁体   中英

Laravel - Check if username already exists before submitting form with jQuery AJAX

I've made a registration form with a lot of fields. Since when I submit data and the validator redirects back with errors some inputs are empty and the user has to lose time refilling them, I want to implement some front-end validations. I'm stuck on checking if an username is already used on submit button press becasuse I'm not expert about AJAX.

In the AuthController I've created a function that returns a Json containing a response in relation of existence or not of the username in the database.

class UserAuthController extends Controller
{
    public function isUserNameInUse( $username )
    {
        if (Auth::where('username', $username) != null){
            return [ 'is_used' => 1 ];
        }

            return [ 'is_used' => 0 ];
    }
}

In the routes.php there are these lines:

Route::group([ 'as' => 'api', 'prefix' => 'api', 'namespace' => 'Api'], function () {

     Route::group([ 'as' => 'auth', 'prefix' => 'auth'], function () {
          Route::any('/is_username_in_use/{username}', [
            'as' => 'isUserNameInUse',
            'uses' => 'UserAuthController@isUserNameInUse']);


    });

});

The view is like that (only a piece of the form):

<form action="{{ route('web.company.postSignup') }}" method="post" id="signup-form" class="form-horizontal">
            {!! csrf_field() !!}
            @include( 'errors.handler' )

                            <label for="username">
                                {{ _('Username*') }} </label>
                            <input type="text" class="form-control" name="username" id="username"
                                   value="{{ Input::old('username') }}" required>

                            <label for="password">
                                {{ _('Password*') }}
                            </label>

                            <input type="password" class="form-control" name="password" id="password"
                                   value="{{ Input::old('password') }}" onchange="form.confirmPassword.pattern = this.value;"
                                   required>

                            <label for="confirmPassword">
                                {{ _('Confirm Password*') }}
                            </label>

                            <input type="password" class="form-control" name="confirmPassword" id="confirmPassword" required>
                            <button class="btn btn-warning" id="submit-btn" type="submit">{{ _('Sign Up') }}</button>

</form> 

This is the script, for now I've only tried to log the response of the controller, but it prints anything.

$(document).ready(function () {
    $('form#signup-form').submit(function () {
         var input_username = $('input[name=username]').val();
         console.log(input_username);

        $.getJSON('/api/auth/is_username_in_use/' + input_username, function (json) {

            console.log(json);


            });
            return false;
        });

    });

You should change return [ 'is_used' => 0 ]; into return Response::json([ 'is_used' => 0 ]); and add use Response; to the top of your controller.

There is no need to make an explicit check if user name is in use. You may skip this part and instead, when you storing your user's data validate them accordingly.

An example of this might be

public function store(Request $request)
{
    $this->validate($request, [
        'username' => 'required|unique:users',
        'password' => 'required|confirmed'
    ]);

    // process your logic
}

This way, if validation failed, you'll get a json response object containing error messages.


Note, this will work if you're on Laravel 5 . If you are on 4.* refer to documentation for validation part.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM