Search code examples
validationlaravel-bladelaravel-validation

How to validate 2 separated string with Validator in laravel 6?


I would like to make a validation for the input string using Laravel 6 with the input condition as below.

userNo = "5031234567"  => Len = 10 digits and must start with 503.

I tried to validate userNo with Laravel Validator as below and the result = Passed.

$validator = Validator::make($data, [
   'userNo' => 'required|regex:/^(\b[503])([0-9]{9})$/'
]);

Above was normal flow before but now I have a new rule to have the second userNo format as below condition.

userNo = "504123456"  => Len = 9 digits and must start with 504.

I would to validate the new rule.

I tried to combine the above Strings of userNo into the below validation but error 500.

$validator = Validator::make($data, [
   'userNo' => 'required|regex:/^(\b[503|504])([0-9]{9})$/'
]);

Now, I tried separating with the if...else.. statement to validate with the below code and it throws "The userNo format is invalid."

if(ubstr($data["telephone"],0,3) == '504')
{
   $validator = Validator::make($data, [
      'userNo' => 'required|regex:/^(\b[504])([0-9]{9})$/'
   ]);
} else
{
   $validator = Validator::make($data, [
      'userNo' => 'required|regex:/^(\b[503])([0-9]{9})$/'
   ]);
}

This is the simple return or response if validation fails.

if ($validator->fails()) {
   return response()->json([
     'ResultCode' => 4005,
      'Detail' => $validator->errors()
   ], 401);
}

Could anyone have a suggestion to handle this?

Thank you in advance.


Solution

  • $validator = Validator::make($data, [
        'userNo' => [
            'required',
            'regex:/^(503|504)[0-9]{9}$/'
        ]
    ]);
    
    if ($validator->fails()) {
        return response()->json([
            'ResultCode' => 4005,
            'Detail' => $validator->errors()
        ], 401);
    }
    

    This will work fine