1

How can I pass some variable in a custom validation rule from the controller validator?

For example:

      class RegisterController extends Controller {

             $someVariableINeed = 2

             protected function validator(array $data) {
                    return Validator::make($data, [
                                'name' => 'required|string|max:255',
                                'email' => 'required|string|email|max:255|unique:users',
                                'password' => 'required|string|min:6|confirmed',
                                'someField' => ['required', new \App\Rules\CustomValidationRule]
                    ]);
                }
 .....

        }

And the \App\Rules\CustomValidationRule :

.....

     public function passes($attribute, $value) {
       if ($value == 1 && $someVariableINeed == 2) {
        return true
       }
       return false
     }

.....

I need to pass variable $someVariableINeed from the RegisterController to the \App\Rules\CustomValidationRule.

Something similar to how max:255 works. I want to pass into my custom rule the 255.

1
  • i think you can added it in custom $errors array Commented Feb 27, 2019 at 18:26

1 Answer 1

2

Add it as a custom validation parameter like this:

class CustomValidationRule extends Rule
{
    public $max;

    public function __construct($max = 255)
    {
        $this->max = $max;
    }
}

And you could access it in the passes method like $this->max

And initiate the value like this:

new CustomValidationRule(255)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.