Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Roni's avatar
Level 33

Use a regex validation ONLY if another field is missing.

Hi, I've got a form request, that has a basic requirement.

  1. It needs valid npa phone numbers.
  2. It only needs one phone number even though more than one is asked for.

Right now, I can get either to work, but not both

OPTION 1 Works for requiring only one phone.


 public function rules()
   {
      return [
   
         'cell_phone' => 'required_without:home_phone',
         'home_phone' => 'required_without:cell_phone',
    
      ];
   }

OPTION 2 Works for validating an npa phone number

 public function rules()
   {
      return [
         'cell_phone' => 'npa_phone',
         'home_phone' => 'npa_phone',
    
      ];
   }

NPA is in AppServiceProvider Boot method:

 public function boot()
    {
       Validator::extend('npa_phone', function($attribute, $value, $parameters)
       {
          $attribute = preg_replace('/\D/', '', $value);
          $pattern = '~^\(?([2-9][0-9]{2})\)?([2-9](?!11)[0-9]{2})([0-9]{4})$~';
          return preg_match($pattern, $value);
       });
    }

What I'm trying to accomplish is the following:

  return [
         'cell_phone' => 'required_without:home_phone|npa_phone',
         'home_phone' => 'required_without:cell_phone|npa_phone',
     
      ];

Any advice appreciated.

0 likes
1 reply
Roni's avatar
Roni
OP
Best Answer
Level 33

Damn, it took a while to figure this one out, but essentially you need to give the fields the ability to be nullable

return [
         'home_phone' => 'required_without:cell_phone|nullable|sometimes|npa_phone',
         'cell_phone' => 'required_without:home_phone|nullable|sometimes|npa_phone',
      ];

Please or to participate in this conversation.