Tim
Tim

Reputation: 340

how to call laravel validation rules in a closure function in laravel?

I wish to skip the captcha validation if the account,which maybe a email or mobile, has been captcha validated.

so I write a colsure function. if the session('captcha_validated_reset_account') equals to the account which user input, it will skip the captcha validation.

if not, the program will call a laravel validation rule like "required|captcha"(captcha' comes from https://github.com/mewebstudio/captcha).

The problem is I don't know how to call validation rule in a closure,I tried return 'required|captcha' but it not work as intended.

'captcha' => function($attribute, $val, $fail) use ($request) {
    if (
        ! empty(session('captcha_validated_reset_account'))
        && session('captcha_validated_reset_account') == $request->input('account')
    ) {
        return;
    } else {
        Rule::required... //and call a rule named 'captcha' to validate the captcha code from user input
        //return 'required|captcha';
    }
}

Is any way I can call laravel validation rules in a closure function?

Upvotes: 6

Views: 6720

Answers (1)

nakov
nakov

Reputation: 14268

You should put the closure in an array:

'captcha' => [ function ($attribute, $val, $fail) use ($request) {
    if (
        empty(session('captcha_validated_reset_account'))
        && session('captcha_validated_reset_account') != $request->input('account')
    ) {
        $fail($attribute . ' is required.');
    }
}]

Note that I've changed the condition.

Upvotes: 3

Related Questions