I am currently using Laravel 8 and doing form validation using the built in available validation rule regex
. Currently this project is not able to be edited. So no creating new validation rules using the php artisan make:rule
command. The reason for this is because I'm currently using Pterodactyl Panel (which is a video game server panel that I don't want to be forced to edit and then overwrite my changes later on once Pterodactyl Panel updates... Their update script breaks any changes made by the user.)
So I'm stuck with the generic regex
validation rule, which uses the preg_match()
function built into PHP. I can't use the preg_match_all()
function as thats not how Laravel's Available Validation Rules are set up.
I'm currently trying to validate one to three comma separated values, with or without spaces after the comma. If a user enters in a forth comma separated value, I want it to fail.
Example Valid Strings:
hello,world,test
hello, world, test
hello, world,test
hello,world, test
hello
hello,test
hello, test
Examples of invalid strings are:
hello.world.test
hello world
hello world test
hello world test test
hello,world,test,test
hello,world, test,test
hello,world,test,
hello,world,
hello,
My current regex that works is: \w (\,\w ){1,2}
I'm assuming due to this two arrays OR an issue with my regex, whenever i use the string hello,world,test,test
laravel is still thinking that this is valid and does not throw an error. It just accepts the string and moves on.
CodePudding user response:
You can use this pattern: ^\w (?:(?:\, ?\w ){1,2})?$
See Regex Demo and See PhpLiveRegex Demo
Explanation:
?
This makes space after a comma becomes optional.?:
This makes a regex group non-captured. the reason you get an array with two-element is that one of them is matched string and others are captured group (everything between "(" and ")") so with ?: in the start of every group that becomes a non-capturing group.^
Start of the string.$
End of the string.