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

catchbobbie's avatar

Laravel validation starts_with REGEX

I have some fields on the form. 4 of them are required if one of the field starts_with "999". I tried using the following.

'description' => 'required_if:part_number,starts_with:999'

But this only works if the "part_number" is exactly 999. If I put 999xx, it fails. I am not sure how to use RegEx with my case.

0 likes
3 replies
LaryAI's avatar
Level 58

To use a regular expression with Laravel validation, you can use the regex rule. In this case, you can use the starts_with function to check if the part_number starts with "999", and then use a regular expression to check if the other fields are filled in.

Here's an example of how you can modify your validation rule:

$rules = [
    'part_number' => 'required|starts_with:999',
    'field1' => 'required_if:part_number,regex:/^999/',
    'field2' => 'required_if:part_number,regex:/^999/',
    'field3' => 'required_if:part_number,regex:/^999/',
    'field4' => 'required_if:part_number,regex:/^999/',
];

In this example, the field1, field2, field3, and field4 fields are required if the part_number starts with "999". The regex rule is used to check if the part_number starts with "999" before checking if the other fields are filled in.

Note that the regular expression /^999/ matches any string that starts with "999". The ^ character matches the beginning of the string, and the 999 characters match the literal string "999".

Hope this helps!

click's avatar

I don't think what you want is possible in 1 default laravel validation rule, but if it is somebody will reply.

You can create your own rule that does it: https://laravel.com/docs/10.x/validation#custom-validation-rules. For exampel you could create a rule called RequiredIfStartsWith() in such a way you end up with required_if_starts_with:part_number,999 where arg1 = the field and arg2 = the value it should start with.

For the quick win you can use closures: https://laravel.com/docs/10.x/validation#using-closures

Untested, but i think something like this should work for you:

'description' => [
   function (string $attribute, mixed $value, Closure $fail) {
            if (str_starts_with(request()->part_number, '999') && blank($value)) {
                $fail("The {$attribute} is required when part number starts with 999.");
            }
        },
],
catchbobbie's avatar

@click Thanks. I ended up creating a custom "DataAwareRule" for my situation.


class RequiredIfStartsWith implements Rule, DataAwareRule
{
     
    public function passes($attribute, $value)
    {
        $dataValue = $this->data['part_number'];
        return str_starts_with($dataValue, '999') && blank($value) ? false : true;
    }

}
					

and using it in the controller like so,

quantity' => [new RequiredIfStartsWith()]

Please or to participate in this conversation.