How to use sometimes rule in Laravel 5 request class

后端 未结 4 502
南笙
南笙 2021-02-12 10:56

I have the following request class:



        
相关标签:
4条回答
  • 2021-02-12 11:37

    You can attach a sometimes() rule by overriding the getValidatorInstance() function in your form request:

    protected function getValidatorInstance(){
        $validator = parent::getValidatorInstance();
    
        $validator->sometimes('dob', 'valid_date', function($input)
        {
            return apply_regex($input->dob) === true;
        });
    
        return $validator;
    }
    
    0 讨论(0)
  • 2021-02-12 11:43

    There is a documented way to make changes to the request's validator instance in Laravel 5.4. You should implement the withValidator method for that.

    Based on the example from @lukasgeiter's answer, you may add the following to your request class:

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator($validator)
    {
        $validator->sometimes('dob', 'valid_date', function ($input) {
            return apply_regex($input->dob) === true;
        });
    }
    

    By doing this you don't have to worry about overriding internal methods. Besides, this seems to be the official way for configuring the validator.

    0 讨论(0)
  • 2021-02-12 11:44

    You just need to add the dob key to the array you are returning, along with the validation ruleset to follow, including sometimes.

    In this case:

    'dob' : 'sometimes|required|regex:/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/|valid_date'
    
    0 讨论(0)
  • 2021-02-12 11:47

    According to your comment

    I want the rule valid_date to only run if the regex rule returns true. Otherwise the valid_date rule errors if the date isnt in the right format.

    Validator::extend('valid_date', function($attribute, $value, $parameters)
        {
           \\use the regex here instead
    
            if (!preg_match('/[0-9]{2}\/[0-9]{2}\/[0-9]{4}/', $value)) return false; 
    
    
            $pieces = explode('/', $value);
            if(strpos($value, '/')===FALSE) {
                return false;
            } else {
                if(checkdate($pieces[1], $pieces[0], $pieces[2])) {
                    return true;
                } else {
                    return false;
                }
            }
        });
    
    
    $validator = Validator::make($data, [
       'first_name' => 'required',
        'last_name' => 'required',
        'email'     => 'required|email|unique:users,email',
        'dob'       => 'required|valid_date',
        'mobile'    => 'required',
        'password'  => 'required|confirmed'
    ]);
    
    0 讨论(0)
提交回复
热议问题