Suppose we want to ask the user at least one of two contacts via the input form: a phone and / or an email address. This means that in the validation rules there will be the required_without rule for both fields:

 $this->validate($request, [ 'email' => 'required_without:tel|email', 'tel' => 'required_without:email|regex:/(01)[0-9]{9}/' ], $messages); 

We need to validate the data format only when they are entered, but in the code above the format is always checked. Since we need to know at least one contact, the rule sometimes does not fit.

    4 answers 4

    With the correctness of the code I will not bother (substitute the variable value sources themselves), briefly the essence:

     $fields = []; if( isset( $email ) AND is_string( $email ) AND mb_strlen( $email ) ): $fields[ 'email' ] = 'required_without:tel|email'; endif; if( isset( $tel ) AND is_string( $tel ) AND mb_strlen( $tel ) ): $fields[ 'tel' ] = 'required_without:email|regex:/(01)[0-9]{9}/'; endif; $this->validate($request, $fields, $messages); 

    I would do something like this.

      Try using the bail rule.

      If a rule is specified, the validator will not go further if the previous rule has not fulfilled, perhaps in your case it will help:

       $this->validate($request, [ 'email' => 'bail|required_without:tel|email', 'tel' => 'bail|required_without:email|regex:/(01)[0-9]{9}/' ], $messages); 
      • Thank you for your reply. Doesn't “Validator go further” does not mean that the data will be invalid, and therefore sending will not work? - Bokov Gleb
      • @GurebuBokofu it will not go further in the current field, that is, if required_without:tel not true, then the email will not check and will go to check tel , and similarly with the tel field, and you just need it - Yaroslav Molchan
      • You say everything correctly, but they don’t work - it still goes through a format check. I understood why: if at least one of the fields is filled, required_without returns true for both fields, and therefore bail does not stop the check and it reaches the last condition. - Gleb
      • @GurebuBokofu try the required_if:tel, for email required_if:tel, and likewise for the email, a comma at the end specifically because we check 2 parameters for emptiness, in theory it should work - Yaroslav Molchan

      Try using the nullable rule nullable

       $this->validate($request, [ 'email' => 'nullable|required_without:tel|email', 'tel' => 'nullable|required_without:email|regex:/(01)[0-9]{9}/' ], $messages); 

        The required_without rule should be set only on one of the fields.

         $rules = [ 'email' => 'email|min:6', 'tel' => 'required_without:email|regex:/(01)[0-9]{9}/' ]; $messages = [ 'tel.required_without' => 'Укажите почту либо телефон, пожалуйста.', ]; $this->validate($request, $rules, $messages);