vinubangs's avatar

How to Validate a Laravel Form Using jQuery Ajax

I'm trying to validate a Laravel form via jQuery/Ajax. I have two form fields: 'email' and 'contact.' If anyone types in email and it's already registered then it will show "Email id already registered". And same like in contact. I have done it in PHP. However, it's not working in the view.

register.blade.php


<form method="POST" action="{{ route('register') }}" id="Frm_sign" name="Frm_sign">
    {{csrf_field()}}
    <div class="form-group col-md-6 col-sm-6">
        <label for="arrival">Contact No*</label>
        <input type="text" class="form-control input-sm required digits" id="contact" name="contact"
               value="{{ old('contact') }}" placeholder="">
    </div>

    <div class="form-group col-md-6 col-sm-6">
        <label for="arrival">Email id*</label>
        <input type="text" class="form-control input-sm email required" id="email" name="email"
               value="{{ old('email') }}" placeholder="">
    </div>

    <div class="col-md-12 col-sm-12">
        <div class="form-group col-md-3 col-sm-3 pull-right">
            <input type="submit" class="btn btn-primary" value="Submit" name="submit"/>
        </div>
    </div>
</form>

<!-- form validation -->
<script type="text/javascript">
    $(document).ready(function () {
// - validation
        if ($('#Frm_sign').length > 0) {
            $('#Frm_sign').validate({
                rules: {
                    email: {
                        remote: {
                            url: "{{url("varifyemail")}}",
                            type: "GET",
                            data: {
                                action: function () {
                                    return "1";
                                },
                            }
                        }
                    },
                    contact: {
                        maxlength: 10,
                        minlength: 10,
                        remote: {
                            url: "{{url("varifycontact")}}",
                            type: "GET",
                            data: {
                                action: function () {
                                    return "2";
                                },
                            }
                        }
                    },
                    password: {
                        equalTo: "#repass"
                    }
                },
                messages: {
                    email: {
                        remote: "Email id already registred"
                    },
                    contact: {
                        remote: "Mobile number already registred",
                        maxlength: "Please enter valid mobile number",
                        minlength: "Please enter valid mobile number"
                    },
                    password: {
                        equalTo: "Password is not equal"
                    }
                },

                submitHandler: function (form) {

                    form.submit();
                },
                errorPlacement: function (error, element) {
                    error.appendTo(element.parent());
                }
            });
        }
    });
</script>

In Ajax, there is password also but it's working, so I didn't write the password field here.

Route

Route::get('varifyemail','Auth\RegisterController@varifyemail');
Route::get('varifycontact','Auth\RegisterController@varifycontact');

RegisterController

public function varifyemail(Request $request)
{
    $email1 = User::where('email', $request->email)->get();
    if($email1->email > 0)
    {
        echo json_encode(false);
    } else {
        echo json_encode(true);
    }
}

public function varifycontact(Request $request)
{
    $contact1 = User::where('contact', $request->contact)->get();
    if($contact1->contact > 0)
    {
        echo json_encode(false);
    } else { 
        echo json_encode(true);
    }
}
0 likes
14 replies
signar's avatar

@vinubangs I'm not familiary with the validate plugin for jQuery so I can't help you there. But I see some problems in your controller. Try this:

public function varifyemail(Request $request)
{
    $email = User::where('email', $request->email)->get();

    if (count($email) > 0) {
        return false;
    } 

    return true;
}

public function varifycontact(Request $request)
{
    $contact = User::where('contact', $request->contact)->get();

    if (count($contact) > 0) {
        return false;
    }

    return true;
}

$email and $contact will be arrays so you can't reference the email or contact field directly. You could if you used ->first() instead of ->get().

Laravel will automatically return with JSON if the request was an AJAX request so there is no need to use echo json_encode()

vinubangs's avatar

@SIGNAR - I tried, but error is

(1/1) UnexpectedValueException The Response content must be a string or object implementing __toString(), "boolean" given.

signar's avatar

@vinubangs Oops! My bad! Try this instead:

public function varifyemail(Request $request)
{
    $email = User::where('email', $request->email)->get();

    if (count($email) > 0) {
        return false;
    } 

    return response()->json['success' => true];
}

public function varifycontact(Request $request)
{
    $contact = User::where('contact', $request->contact)->get();

    if (count($contact) > 0) {
        return false;
    }

    return response()->json['success' => true];
}
vinubangs's avatar

@SIGNAR - (1/1) FatalErrorException syntax error, unexpected '=>' (T_DOUBLE_ARROW), expecting ']'

in RegisterController.php line 62

signar's avatar

@vinubangs It's not going too well today :) forgot parathesis around json

return response()->json(['success' => true]);
vinubangs's avatar

@SIGNAR - (1/1) UnexpectedValueException The Response content must be a string or object implementing __toString(), "boolean" given.

vinubangs's avatar

@CAC - I want to validate form without reload. And I want to do this thing with AJAX way.

And I have already added LARAVEL validation in my form.

signar's avatar

@vinubangs The problem is not with the controller response. The problem is the query because you don't send through the correct data.

For your email validation you need to send through the email address to verify like so:

email: {
    remote: {
        url: "{{ url('varifyemail') }}",
        type: "GET",
        data: {
            email: function () {
                return $('#email').val();
            },
        }
    }
},

Do the same for the contact field:

data: {
    contact: function () {
        return $('#contact').val();
    },
}
vinubangs's avatar

@SIGNAR - I updated my controller by:

public function varifyemail(Request $request)
{
    $email = User::where('email', $request->email)->get();

    if (count($email) > 0) {
        return response()->json(['false' => false]);
    } 

    return response()->json(['success' => true]);
}

public function varifycontact(Request $request)
{
    $contact = User::where('contact', $request->contact)->get();

    if (count($contact) > 0) {
        return response()->json(['false' => false]);
    }

    return response()->json(['success' => true]);
}

And view ajax is:

<script type="text/javascript">
$(document).ready(function() {
// - validation
    if($('#Frm_sign').length > 0){
        
        $('#Frm_sign').validate( {
        rules:{
        
         email:{
                       
                       remote: {
                                url: "{{url("varifyemail")}}",
                                type: "GET",
                                data: {                                          
                                         email: function() {
            return $( "#email" ).val();
          }
                                      }                         
                          
                               }
              },
              
         contact:{
                       
                       maxlength:10,
                       minlength:10,
                       remote: {
                                url: "{{url("varifycontact")}}",
                                type: "GET",
                                data: {                                          
                                         contact: function() {
                                                     return $( "#contact" ).val();
                                                   }
                                      }                         
                          
                               }
              },
              
              
        
         password : {
                      equalTo: "#repass"
            }
           
          },
        messages: {
           
          email:      {
            
                        remote:"Email id already registred"
                        },
         contact:          {
                        remote:"Mobile number already registred",                       
                        maxlength : "Please enter valid mobile number",
                        minlength : "Please enter valid mobile number"
                        },
         password:          {
                        equalTo:"Password is not equal"
                        }
        
                   },
        
        submitHandler: function (form) {
                  
            form.submit();
        },
         errorPlacement: function (error, element) {
                error.appendTo(element.parent());
        }
        
        
        });
        
    }
    
});
</script> 

Now no error. And in my console everything is good. And it is showing {"success":true}.

But message for email or contact is not showing, if email or contact exist.

signar's avatar
signar
Best Answer
Level 27

@vinubangs You need to tweek your response from the controller. I don't know what response the jQuery validation plugin expects.. From what I can gather from the documentation, you only need to return true or false as a string in JSON.

return response()->json("true");

or

return response()->json("false");
1 like
towhid's avatar

HEllo @signar ,

i have one issue , if my data is exist its show perfect , but if my data is not exist ,. its also show validation error show .. please make sure how to do solve that ? thank you

Please or to participate in this conversation.