1

I want to validate my form without pressing the submit button in laravel. I have some codes here but only the email format is invalid is working. Can someone tell me what should I do? Im just new to ajax

PS: The message that I get when I enter a valid email {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

Blade

  <input  type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Email" required value="{{ old('inputEmail') }}">

Ajax

   $(document).ready(function () {
    const emailValidation = document.querySelector('#inputEmail');
    const mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; 
    emailValidation.addEventListener('blur', e => { 
      if (emailValidation.value.match(mailformat)) {

        $.ajax({
          type: 'get',
          url: '/emailValidation', 
          _token: "{{ csrf_token() }}",
          data: {
            'emailValidation': emailValidation.value, 
          },
          success: function (data) {
            if (data.validOrNot === "not taken"){
              console.log("it works!");
            } else {
              console.log("email taken!");

            }
          },
          error: function (error) {
            console.log(error);
          }
        });
      } else {

        console.log("Email format is invalid!");

      }
    });
  });

Controller

 public function emailValidation(Request $request){
        // $user = new User;
        $user = User::where('email', '=', Input::get('inputEmail'))->first();
        $emailPassed = $request->emailValidation;

        if ($user===null)
          return response()->json(['validOrNot' => 1]);
        else
          return response()->json(['validOrNot' => 0]);


      }

Route

    Route::get('/emailValidation', 'TeachersController@emailValidation');

1 Answers1

2

If you have a look at the official documentation, Laravel has it's own email validation rule as well as a unique validation rule and, in my opinion it's always better to do a server side validation of the inputs.

There are many reason why a frontend validation is a risk. Have a look at this question as example.

Also, you regular expression is wrong. I haven't tested it EDIT: I've tried it in regexr.com and it doesn't work but there are a lot of topics as well as this question that can give you a much more precise regular expression.

Anyway, since you're making an Ajax call to the backend for the validation, you should change your code as follows:

$(document).ready(function() {
  const emailValidation = document.querySelector('#inputEmail');

  emailValidation.addEventListener('blur', e => {
    // Let the backend do all the validation magic on blur
    $.ajax({
      type: 'get',
      url: '/emailValidation',
      _token: "{{ csrf_token() }}",
      data: {
        'email': emailValidation.value,
      },
      success: function(data) {
        // No need to check the data since it's a valid e-mail
      },
      error: function(error) {
        console.log(error);
      }
    });
  });
});

and in your controller function:

public function emailValidation(Request $request) {
  // Validation
  $this->validate($request, [
    'email' => 'required|email|unique:users'
  ]);

  // Validation passes. Just send an empty response with 200 status code
  return new Response;
}
IlGala
  • 3,331
  • 4
  • 35
  • 49