使用ajax的Integratin验证规则

时间:2016-12-10 00:00:38

标签: jquery laravel laravel-5

我第一次使用laravel验证ajax,但是我在如何整合它们时遇到了一些问题,我怎么能用我的ajax传达我的laravel验证码?我在我的javascript中有一些验证规则,其中每个数字都是一个规则,我如何将它与我的laravel集成? 我的代码有一个例子:

laravel控制器功能:

 public function saveEmail(Request $request)
    {

        $user = Auth::user();
        $this->validate($request, array(
            'current_email'     => 'required|email|exists:users,email,id,'. $user->id,
            'email'             => 'required|email|unique:users',
            'verify_password'   => 'required'
        ));


        //Verify information user before updating
        if($user->email != $request->current_email){
            dd("Current Email is not the same");
        }

        if(! Hash::check($request->verify_password, $user->password)){
            dd("Password incorrect, will not update");
        }


        //Update Email with Sucess
        $user->email =  $request->email;



    }

Ajax代码:

$(document).ready(function () {

            $("#saveEmail").click(function (event) {
                event.preventDefault();
                saveEmail();
            });

        });

 function saveEmail() {

            var email = $("#current_email").val();
            var new_email = $("#email").val();
            var password = $("#verify_password").val();
            var data = { current_email: email, email: new_email, verify_password: password }
            $.ajax({
                url: "company/saveEmail')}}",
                type: 'POST',
                data: data,
                success: function (result) {
                    if (result == 0) {
                     //Email saved correctlly
                     var text = 'E-mail actualizado';
                     $('#saveOK').text(text);
                     $("#current_email").val("");
                     $("#email").val("");
                     $("#password").val("");
                     $("#ErrorEmail").css({ "display": "none" });
                     }
                     else if (result == 1) {
                     //"Incomplete data"
                     var error1 = 'The data are incomplete';
                     $("#lbtxtEmailError").text(error1);
                     $("#ErrorEmail").css({ "display": "block" });
                     }
                     else if (result == 2) {
                     //"Current email incorrect"
                     var error2 = 'Current email is incorrect';
                     $("#lbtxtEmailError").text(error2);
                     $("#ErrorEmail").css({ "display": "block" });
                     }
                     else if (result == 3) {
                     //"Incorrect format"
                     var error3 = 'The format is incorrect';
                     $("#lbtxtEmailError").text(error3);
                     $("#ErrorEmail").css({ "display": "block" });
                     }
                     else if (result == 4) {
                     //This email is already in use
                     var error4 = 'This email is already in use';
                     $("#lbtxtEmailError").text(error4);
                     $("#ErrorEmail").css({ "display": "block" });
                     }
                     else if (result == 5) {
                     //"Current password incorrect";
                     var error5 = 'Your password is incorrect';
                     $("#lbtxtEmailError").text(error5);
                     $("#ErrorEmail").css({ "display": "block" });
                     }
                     else if (result == 6) {
                     //"This user doesnt exist" id
                     var error6 = 'User doesnt exist';
                     $("#lbtxtEmailError").text(error6);
                     $("#ErrorEmail").css({ "display": "block" });
                     }
                     else if (result == 7) {
                     //"New email already exist"
                     var error7 = 'New email alreadu exist ';
                     $("#lbtxtEmailError").text(error7);
                     $("#ErrorEmail").css({ "display": "block" });
                     }

                }

            })
        }

1 个答案:

答案 0 :(得分:0)

在正常线程请求和ajax请求之间进行验证请求的一个重要区别是验证器在发生故障时如何响应。从文档中,这是响应的制作方式(失败时):

  

如果传入请求是ajax请求,则不会生成重定向。相反,具有422状态代码的HTTP响应将返回到包含验证错误的JSON表示的浏览器。

A 422很棒,因为这意味着我们可以在承诺的.error()回调中观察到失败。

$.ajax({
    //routes, urls, data, etc
}).done(function(response){
    //this all worked well
}).error(function(data){
    //walk the object for your data
    console.warn(data);
});

此外,泰勒警告过fat controllers。我们应尽可能尝试使用抽象逻辑。相反,我们应该做出正确的Request

php artisan make:request SaveEmailRequest

然后在App\Http\Requests\SaveEmailRequest打开我们的文件,找到public function authorize()功能。在这里,我们将检查用户的电子邮件和请求电子邮件是否匹配:

/**
 * @returns boolean
 */
public function authorize()
{
    $flag = isset($this->current_email) && $this->current_email == auth()->user()->email);
    $flag = Hash::check($this->verify_password, auth()->user()->password);

    return $flag;
}

然后我们可以将规则移到我们请求的public function rules()

/**
 * @return mixed
 */
public function rules()
{
    return [
        'current_email'     => 'required|email|exists:users,email,id,'. auth()->user()->id,
        'email'             => 'required|email|unique:users',
        'verify_password'   => 'required'
    ];
}

最后我们只需要在我们的控制器中使用它:

public function saveEmail(App\Http\Requests\SaveEmailRequest $request) 
{
    auth()->user()->update([
        'email' => $request->email
    ]);
}

你会注意到我们不会返回任何上述内容。那是因为我们不需要。响应将以200的形式返回,它将进入我们承诺的.done()函数。我们不必担心猜测。

如果发生任何故障(哈希检查,电子邮件不匹配,密码不匹配),则会返回422响应,并且可以在{{找到错误消息1}} data方法的参数。

希望这可以帮到你。