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

Kenneth_H's avatar

Custom validation rule and regex

Hi I am trying to add some new validation rules to an app. There is a requirement, that if a certain field has a value above 100000, then this specific fields should be required. Additionally, the field should also contain "https://", as the user is required to provide a URL. Currently it looks a little like this:

$this->validate($request,
            [
                'date'                => 'required|date',
                'order_total'        => 'required|integer',
                'before_screenshot' => [Rule::requiredIf(function () use ($request) {
                    if ($request->input('order_total') > 100000)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }
                }), 'regex:/^https:\/\//m'],
            ]);

Currently, it is required if the order_total field is above 100k, but it also validates the regular expression every time. So even if the field is not required, then it still gives a validation error. Can I make it so that regex validation is only performed if there is actually provided a value?

0 likes
2 replies
dragoneyes96's avatar

I think this is not the best solution but you can try this

$rules = [
    'date'                => 'required|date',
    'order_total'        => 'required|integer',
];

if ($request->input('order_total') > 100000) {
    $rules = array_merge_recursive($rules, [
        'before_screenshot' => 'required|regex:/^https:\/\//m'
    ];
}

$this->validate($request, rules)
                        
vandan's avatar

$this->validate(request(), [

'projectName' => 

    array(

        'required',

        'regex:/(^([a-zA-Z]+)(\d+)?$)/u'

    )

];

Please or to participate in this conversation.