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

fylzero's avatar
Level 67

Is it possible to validate string OR number?

I have a form config field that needs to validate if it is a number or string (potentially with spaces).

How can I do this?

I was thinking alpha_num but I don't think that will work with spaces, etc.

Is there a way to check for string OR numeric? Custom rule? What do you think?

Can I just do string|numeric?

Sorry, testing this now, but curious if anyone has a thought on how to tackle this.

0 likes
5 replies
bugsysha's avatar

Also note that \s is any white space character. If you want only space then

'field' => 'regex:/^[a-z0-9 ]+$/i',

// or

'field' => 'regex:/^[a-z0-9 ]*$/i',

i at the end of regex is for case insensitive. So remove it if you want to make it case sensitive.

fylzero's avatar
fylzero
OP
Best Answer
Level 67

Thanks for the responses, I actually wound up not needing this but went for this approach at first...

$rules = [
    'thing1' => 'required'
];

if (gettype(request()->thing2 === 'numeric')) {
    $rules['thing2'] => 'numeric';
} else {
    $rules['thing2'] => 'string';
}

return $rules;
bugsysha's avatar

@fylzero

Super ugly.

$rules = [
    'string' => ''
    'numeric' => ''
];

return $rules[gettype($request->thing2)];

That can even be inlined.

Please or to participate in this conversation.