How do I validate forms in Laravel by not clicking submit button


I have a form that has multiple inputs in it. I want the email validation occurs after the user type his email and focus another text box and also by not clicking the submit button. I'm not good with frontend like ajax and jquery. Can someone tell me what should I do? Thanks in advance.
Form


                  {{ Form::open(['method' => 'POST', 
                    'onsubmit' => 'return LoadingOverlay()', 
                    'route' => ['admin.sysads.store'], 
                    'class' => 'form-horizontal', 
                    'files' => true]) 
                  }}

                    {{ csrf_field() }}

                    <input id="formname" type="hidden" name="profile_update">
                    <input id="inputPhonex" type="hidden" name="inputPhonex">


                    @if(Auth::user()->role == 0)
                      <div class="form-group has-feedback {{ $errors->has('school_id') ? ' has-error' : '' }}">
                        <label for="school_id" class="col-sm-2 control-label">School</label>

                          <div class="col-sm-10">
                            <select class="form-control select2" style="width: 100%;" name="school_id" required>
                              <option></option>
                              @foreach($global_schools as $global_school)
                              <option value="{{ $global_school->id }}">{{ $global_school->description }}</option>
                              @endforeach
                            </select>
                            @if ($errors->has('school_id'))
                                <span class="help-block">
                                    <strong>{{ $errors->first('school_id') }}</strong>
                                </span>
                            @endif
                          </div>
                      </div>
                    @endif

                    <div class="form-group has-feedback {{ $errors->has('inputEmail') ? ' has-error' : '' }}">
                      <label for="inputEmail" class="col-sm-2 control-label">Email</label>

                      <div class="col-sm-10">
                        <input type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Email" required value="{{ old('inputEmail') }}">
                        @if ($errors->has('inputEmail'))
                          <span class="help-block">
                              <strong class="text-danger">{{ $errors->first('inputEmail') }}</strong>
                          </span>
                        @endif
                      </div>
                    </div>

                    <div class="form-group">
                      <label for="inputPassword" class="col-sm-2 control-label">Default Password</label>

                      <div class="col-sm-10">
                        <input type="text" class="form-control" id="inputPassword" name="inputPassword" placeholder="Default Password" required value="12345" readonly>
                      </div>
                    </div>

                    <div class="form-group">
                    <label for="inputFName" class="col-sm-2 control-label">First Name</label>

                      <div class="col-sm-10">
                        <input type="text" class="form-control" id="inputFName" name="inputFName" placeholder="First Name" required value="{{ old('inputFName') }}">
                      </div>
                    </div>

                    <div class="form-group">
                      <label for="inputLName" class="col-sm-2 control-label">Last Name</label>

                      <div class="col-sm-10">
                        <input type="text" class="form-control" id="inputLName" name="inputLName" placeholder="Last Name" required value="{{ old('inputLName') }}">
                      </div>
                    </div>

                    <div class="form-group has-feedback {{ $errors->has('inputGender') ? ' has-error' : '' }}">
                      <label for="inputGender" class="col-sm-2 control-label">Gender</label>

                      <div class="col-sm-10">
                        <select class="form-control select2" style="width: 100%;" name="inputGender" required>
                            <option></option>
                            <option value="1">Male</option>
                            <option value="2">Female</option>
                        </select>

                        @if ($errors->has('inputGender'))
                            <span class="help-block">
                                <strong>{{ $errors->first('inputGender') }}</strong>
                            </span>
                        @endif
                      </div>
                    </div>


                    <div class="form-group">
                      <label for="inputBirthday" class="col-sm-2 control-label">Birthday</label>

                      <div class="col-sm-10">
                        <div class="input-group date">
                          <div class="input-group-addon ">
                            <i class="fa fa-calendar"></i>
                          </div>
                          <input type="text" class="form-control pull-right" id="inputBirthday" name="inputBirthday" 
                          placeholder="yyyy-mm-dd" value="{{ old('inputBirthday') }}" required>
                        </div>
                        <!-- /.input group -->
                      </div>
                    </div>
                    <!-- /.form group -->


                    <div class="form-group">
                      <label for="inputAddress" class="col-sm-2 control-label">Address</label>

                      <div class="col-sm-10">
                        <input type="text" class="form-control" id="inputAddress" name="inputAddress" placeholder="Address" value="{{ old('inputAddress') }}" required>
                      </div>
                    </div>

                    <div class="form-group has-feedback {{ $errors->has('inputPhone') ? ' has-error' : '' }}">
                      <label for="inputPhone" class="col-sm-2 control-label">Phone No.</label>

                      <div class="col-sm-10">
                        <input type="tel" class="form-control" id="inputPhone" name="inputPhone" 
                        value="{{ old('inputPhone') }}" required>

                        @if ($errors->has('inputPhone'))
                            <span class="help-block">
                                <strong>{{ $errors->first('inputPhone') }}</strong>
                            </span>
                        @endif
                      </div>
                    </div>

                    <div class="form-group has-feedback {{ $errors->has('inputPhoto') ? ' has-error' : '' }}">
                      <label for="inputPhoto" class="col-sm-2 control-label">Photo (max 612x558)</label>

                      <div class="col-sm-10">
                        <input type="file" id="inputPhoto" name="inputPhoto" placeholder="Photo">
                        @if ($errors->has('inputPhoto'))
                            <span class="help-block">
                                <strong>{{ $errors->first('inputPhoto') }}</strong>
                            </span>
                        @endif
                      </div>
                    </div>

                    <hr>

                    <div class="form-group">
                      <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" class="btn btn-primary">Save</button>
                        <a href="{{ route('admin.sysads') }}" class="btn btn-danger" onclick="return LoadingOverlay();">Cancel</a>
                      </div>
                    </div>

                  {{ Form::close() }}
Controller store method
public function store(ProfileRequestSave $request)
    {

            if (Auth::user()->role == 0) {

                $items = new User;

                if (Auth::user()->role == 0) {
                    $items->school_id = $request->school_id;
                } else {
                    $items->school_id = Auth::user()->school_id;
                }

                $items->email = $request->inputEmail;
                $items->password = bcrypt($request->inputPassword);
                $items->role = 1;

                $items->name = ucfirst($request->inputFName) . ' ' . ucfirst($request->inputLName);
                $items->fname = ucfirst($request->inputFName);
                $items->lname = ucfirst($request->inputLName);

                $items->gender = $request->inputGender;
                $items->birthdate = $request->inputBirthday;
                $items->address = $request->inputAddress;
                $items->phone = $request->inputPhonex;

                //image uploaded
                $photo_path = null;
                if ($request->hasFile('inputPhoto')) {
                     $photo_path = Storage::putFile('public/user/image', $request->file('inputPhoto'));
                } else {
                    $photo_path = '';
                }
                $items->photo_path = $photo_path;

                $items->confirmed = 0;
                $digits = 4;
                $items->confirmation_code = rand(pow(10, $digits-1), pow(10, $digits)-1);

                $items->save();

                //send email
                //user verification
                $user = User::find($items->id);
                $beautymail = app()->make(\Snowfire\Beautymail\Beautymail::class);
                $beautymail->send('emails.user.verification', [
                'user' => $user
                ], function($message) use ($user)
                {
                    $message
                        ->from('safeapp.ph@gmail.com', 'Safe')
                        ->to($user->email, $user->name)
                        ->subject('User Verification');
                });

                return redirect('inx/sysads')->with('success', $this->page_title.' saved');

            } else {
                return redirect('inx/sysads')->with('error', 'Invalid access');
            }

    }
ProfileRequestSave method
class ProfileRequestSave extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'inputEmail' => 'unique:users,email',

            'inputRFID' => 'unique:users,student_school_id|nullable',
            'inputSchoolID' => 'unique:users,student_card_no|nullable',

            'inputFName' => 'required|max:191',
            'inputGender' => 'required|not_in:0',
            'inputPhone' => 'required|regex:/(^[0-9+ ]+$)+/',
            'inputPhoto' => 'image|mimes:jpg,png,jpeg|max:2048|dimensions:max_width=612,max_height=558'
        ];        
    }

    public function messages(){
        return [
            'inputEmail.unique' => 'Email already exists.',
            'inputSchoolID.unique' => 'School ID already exists.',
            'inputRFID.unique' => 'RFID already exists.'
        ];
    }

}
  • 1
    1 word. Javascript. – Ohgodwhy 1 hour ago 
  • what specifically js sir? like keyup function or something? how to i connect that to the controller? – Vince 1 hour ago
1
There's no other way than to do it with javascript. Use the event listener blur. If it's only an email validation like if it's valid or not, then you can handle it with javascript alone. But if you're talking about if that email inputted is already taken then you'd have to do it with AJAX since it'll have to go to your database.
Before anything make sure you have imported jquery library to your page.
In your javascript file
$(document).ready(function () {
    const emailValidation = document.querySelector('#mail');
    const mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; //mail format
    emailValidation.addEventListener('blur', e => { //Event Listener
      if (emailValidation.value.match(mailformat)) {
        // if email is valid, proceed to ajax
        $.ajax({
          type: 'get',
          url: '/emailValidation', // Create a route get
          _token: "{{ csrf_token() }}",
          data: {
            'emailValidation': emailValidation.value, //we pass in the email value to the controller with an id of 'emailValidation'
          },
          success: function (data) {
            if (data.emailValidation === "not taken"){
              console.log("it works!");
            } else {
              console.log("email taken!");
              // place DOM Manipulation
            }
          },
          error: function (error) {
            console.log(error);
          }
        });
      } else {

        console.log("Email format is invalid!");
        // place DOM Manipulation
      }
    });
  });
Create a route with a get method, I'd recommend placing this to a new controller where you'll store your ajax requests.
In your ajaxController (this is a sample name)
public function emailValidation(Request $request){
  $user = new User;
  $emailPassed = $request->emailValidation;
  // Do a query here comparing the passed value from AJAX to your data in the database

  // We pass an if statement to check if email exists in database or not
  if (passed)
    return response()->json(['validOrNot' => 1]); // in ajax we return back json array
  else
    return response()->json(['validOrNot' => 0]);
}
I haven't tested it so not gonna be sure if it'll work for you, but atleast you have a starting point to get on. I'd really recommend learning javascript and AJAX.
  • yes sir thats what i mean. although its hard for me – Vince 1 hour ago
  • 1
    First off, rather than validating in your controller, try to validate it with javascript alone, try practicing adding an EventListener. Use regex format for validation, here's what I use for mail format /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/ – Steven 1 hour ago
  • yes sir im trying... – Vince 1 hour ago

Your Answer

Post a Comment

0 Comments