【问题标题】:Stop form refreshing when validation fails Laravel验证失败时停止刷新表单 Laravel
【发布时间】:2018-08-01 08:09:42
【问题描述】:

我有以下代码:

模态:

<form class="form-signin" role="form" method="POST" action="{{ url('/login') }}">
    <div class="modal fade" id="signinModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        @include('application.errors')
        ...
        <button type="submit" class="btn btn-hp-modal underline btn-signup-modal">Log in</button>
    </div>
</form>

控制器:

public function login( Request $request ) {
    ...
    // If the login attempt was unsuccessful
    return $this->sendFailedLoginResponse($request);
}

protected function sendFailedLoginResponse(Request $request)
{   
    throw ValidationException::withMessages([
        $this->username() => [trans('auth.failed')],
    ]); 
}   

application.errors:

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

我遇到的问题是,单击Log in 后,无论验证成功与否,它都会刷新页面。如果我在刷新页面后打开模式,则会出现该消息,但我希望模式保留以防它实际进入sendFailedLoginResponse

任何帮助将不胜感激!

【问题讨论】:

  • 你不能只用 php 来做,你需要用ajax提交你的表单

标签: php forms laravel validation login


【解决方案1】:

如果您想阻止页面在提交时刷新,您需要使用 JavaScript 进行客户端验证检查。

为了防止表单提交,您需要在表单提交处理程序上使用event.preventDefault()return false

看起来你在这里提交到你的服务器,这意味着你不能做你想做的事。如果要实现客户端验证并防止页面失败时重新加载,则必须使用 JavaScript。

这是一个伪代码示例:

$('#form').submit(function (e) {
    if ($('#username').value() === '') {
        // Show some validation message here...

        // Prevent default and return.
        return e.preventDefault();
    }

    // Submit to API via AJAX call.
});

【讨论】:

    【解决方案2】:

    我找到了另一种方式:

    在验证返回中推送GET 请求以获取一些以前的数据,它不会修复刷新,但至少您可以在用户被重定向时恢复数据:

       // if the validator fails, redirect back to the form
        if ($validator->fails()) {
            //let's send some data back (Orlando,Florida):
            return Redirect::to('auth/register?city=Orlando&State=Florida')
                ->withErrors($validator)
                ->withInput(Input::except('password', 'password_confirmation'));
    
    
        }else{
         //validation success
        }
    

    【讨论】:

      猜你喜欢
      • 2014-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-19
      • 1970-01-01
      • 1970-01-01
      • 2015-05-04
      • 2014-11-01
      相关资源
      最近更新 更多