Как проверить формы в Laravel, не нажимая кнопку «Отправить» - PullRequest
2 голосов
/ 01 октября 2019

У меня есть форма с несколькими входами. Я хочу, чтобы проверка электронной почты происходила после того, как пользователь напечатал свою электронную почту и выделил другое текстовое поле, а также не щелкнув кнопку отправки. Я не очень хорошо разбираюсь в интерфейсе, как ajax и jquery. Может кто-нибудь сказать мне, что мне делать? Заранее спасибо.

Форма


                  {{ 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() }}

Способ хранения контроллера

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

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.'
        ];
    }

}

Ответы [ 5 ]

1 голос
/ 03 октября 2019

Используйте функцию javascripts blur с jquery. А также вы можете использовать собственное правило проверки электронной почты laravel под названием unique, и вы можете сделать проверку на стороне сервера для лучшего. Вы делаете AJAX-вызов, поэтому измените свой код следующим образом.

<script>
  $(document).ready(function() {
  const emailValidation = document.querySelector('#inputEmail');
//should use mailformat regex 
  const mailFormat = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  emailValidation.addEventListener('blur', e => {
//if input matches the regex 
    if(emailValidation.value.match(mailFormat)){
      $.ajax({
      type: 'get',
      url: '/emailValidation',
      _token: "{{ csrf_token() }}",
      data: {
        'email': emailValidation.value,
      },
      success: function(data) {
//valid email or not taken
      alert('valid email');

      },
      error: function(error) {
//email already taken reference from ajax route
        alert('email is taken already!');

      }
    });

  } else{
//if regex match false
    alert('Invalid Email Format');
  }


  });
});

</script>

Контроллер. Просто выполните обычную проверку laravel

  public function emailValidation(Request $request) {

        $this->validate($request, [
          'email' => 'required|unique:users'
        ]);

      }

И вы должны создать маршрут запроса получения

    Route::get('emailValidation', 'YourController@emailValidation');

Надеюсь, это поможет!

1 голос
/ 01 октября 2019

Это очень просто, и вы должны отправить свою форму.

Прежде всего вам нужно всего лишь несколько вещей, которые нужно добавить
Файл Blade:

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

ВыJquery внутри вашего Blade-файла.


Демо:

<script>
   $("#myForm").submit(function(e){
        e.preventDefault(); // this e.preventDefault for prevent from reload after form submit 
     $.ajax({
          method : $(this).attr("method"), // you can use 'post' also. Since you already declared method that's why i just called this from form tag
          url : $(this).attr("action"), // Your Route called here. You can call this way to  "{{ route('admin.sysads.store') }}",

          contentType: false,
          cache: false,
          processData:false,
          data : new FormData(this),
          dataType : 'json' , // Return values data Type.
          success:function(responseData){
            // some code according to your validation and success too
          }
     });

   });
</script>

Процесс возврата изменения файла контроллера.

return response(['success'=>'Process success']); // for validation errors you can just replace 'Process success' with error parameter

Надеюсь, что это будет работать длявы.

1 голос
/ 01 октября 2019

Чтобы удостовериться, что идентификатор электронной почты уже занят или нет, статус показывает


Изменения в Blade-файле:

<input type="email" class="form-control emailValidate" placeholder="Example@email.com">

Js:

$(document).on("keyUp",".emailValidate",function(){
    var email = $(this).val();
    var token = "{{ csrf_token() }}";
    $.ajax({
        method :"post",
        url : "{{ route('email.check') }} ",
        data : {email:email,_token:token},
        dataType:'json',
        success:function(response){
           // Email already taken or not logic here
       },
       error:function(err){
        // error logic here
      }
    });
});

В сети. php

Route::post("/Email-check","YourControllerName@methodName")->name('email.check');

At Controller Method

public function methodName(Request $request){
     $takenOrNot = ModelName::where('columnName',$request->email)->count();
     if($takenOrNot > 0){
        return json_encode(['success'=>1]); // success => 1 for Already taken
     }else{
        return json_encode(['success'=>0]); // You can use this Email Name
    }
}
1 голос
/ 01 октября 2019

Нет другого способа, кроме как сделать это с помощью JavaScript. Используйте прослушиватель событий blur . Если это только проверка электронной почты, например, действительная она или нет, то вы можете справиться с ней только с помощью javascript. Но если вы говорите о том, что введенное письмо уже занято, вам придется сделать это с AJAX, так как оно должно перейти в вашу базу данных.

Прежде чем что-либо убедиться, что вы импортировали библиотеку jqueryна вашу страницу.

В вашем javascript-файле

$(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.validOrNot === "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
      }
    });
  });

Создайте маршрут с помощью метода get, я бы рекомендовал разместить его на новом контроллере, где вы будете хранить ваши ajax-запросы.

В вашем ajaxController (это примерное имя)

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]);
}

Я не проверял его, поэтому не буду уверен, что он будет работать для вас, но по крайней мере у вас есть отправная точка для перехода,Я действительно рекомендую изучать JavaScript и AJAX.

0 голосов
/ 01 октября 2019

Добавьте пустое поле ниже поля ввода электронной почты, как показано ниже:


<input type="email" class="form-control emailValidate" placeholder="Example@email.com">
<div id="msg"></div>



$(document).on("keyUp",".emailValidate",function(){
var email = $(this).val();
var token = "{{ csrf_token() }}";
$.ajax({
    method :"post",
    url : "{{ route('email.check') }} ",
    data : {email:email,_token:token},
    dataType:'json',
    success:function(response){
       // Email already taken or not logic here
       if(response.success == 1){ // you may try this way also if(response.success == "1")
          $("#msg").html("Email Already taken");
       }else{
         $("#msg).html("Valid Email id");
       }
   },
   error:function(err){
    // error logic here
  }
});
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...