santosh limbu thebe
santosh limbu thebe

Reputation: 59

Realtime validation of Email with ajax and laravel(if email is already in database, it says email taken) like in gmail registration page

My Laravel controller class which checks if the email is already stored in the database or not: In my User table, it checks for if email exists in the database or not?

public function checkemail(){
      $userCount = DB::table('users')->where('email', input::get('email'));
      if($userCount->count()) 
      {
          return Response::json(array('msg' => 'true'));
      }
      else 
      {
       return Response::json(array('msg' => 'true'));
      }
}

My Ajax method which checks if email is already stored in database or not? If it is stored in database then it should say email address already taken or else nothing. If email is taken, it shows in red line and if not then nothing. The form name is registration.
url in web.php is

routes::post('checkmail','postcontroller@checkmail');

jQuery

$("#registration").validate({

    errorElement: 'div',
    errorLabelContainer: '.errorTxt',
    ignore: [],

    //following rules for email
    rules: {
        email: {
            required: true,
            email: true,
            remote: {

                url: "checkemail",
                type: "post",
                data: {
                    email: $("input[email='email']").val()
                },
                dataFilter: function(data) {
                    var json = JSON.parse(data);
                    if (json.msg == "true") {
                        return "\"" + "Email address already in use" + "\"";
                    } else {
                        return 'true';
                    }
                }
            }
        },

    },
    messages: {
        email: {
            required: 'Email is required',
            email: 'Please enter a valid email address',
            remote: 'Email already taken'
        }


    },

    errorPlacement: function(error, element) {
        if (element.attr("name") == "email") {
            $(".erroremail").append(error);
        } else {
            error.append($('.errorTxt span'));
        }
    },


    submitHandler: function(form) {
        form.submit();

    }


});

Can anyone help me please, I am quite new to Laravel and ajax as a whole.

Upvotes: 2

Views: 8992

Answers (2)

Bhaumik Pandhi
Bhaumik Pandhi

Reputation: 2673

Textbox blur event

<input type="text" name="email" onblur="duplicateEmail(this)" class="form-control">

jQuery function

  function duplicateEmail(element){
        var email = $(element).val();
        $.ajax({
            type: "POST",
            url: '{{url('checkemail')}}',
            data: {email:email},
            dataType: "json",
            success: function(res) {
                if(res.exists){
                    alert('true');
                }else{
                    alert('false');
                }
            },
            error: function (jqXHR, exception) {

            }
        });
    }

route

Route::post('/checkemail',['uses'=>'PagesController@checkEmail']);

controller

public function checkEmail(Request $request){
    $email = $request->input('email');
    $isExists = \App\User::where('email',$email)->first();
    if($isExists){
        return response()->json(array("exists" => true));
    }else{
        return response()->json(array("exists" => false));
    }
}

you can add your AJAX success handler code, based on true & false

Upvotes: 3

Ohgodwhy
Ohgodwhy

Reputation: 50787

In the controller:

$this->validate(request()->all(), function () {
    return [
        'email' => 'unique:users'
    ];
}); 

Now if the email exists in your database, it will return with an array and then the validation message at the index of the name with a 422 error, which you can catch in the fail callback of your ajax request;

$.ajax({

}).done(function(resp){
    //successful
}).fail(function(errors) {
    // use errors to get the error message
});

In this way, because the server will respond with a 422 error code, if there's a failure on the email it will always hit .fail() and you won't have to worry about doing if() conditionals in your .done() method.

Now you can implement your ajax call in the onblur method of your email input:

$('input[type="email"]').on('blur', function(e) {
     // $.ajax stuff goes here
});

Upvotes: 2

Related Questions