Laravel string validation; all char except #

55 Views Asked by At

I have a Laravel 10 project and I'm trying to validate a string that can include any character (max 11 chars), except the # char

In my controller I tried this code, using regex

$request->validate([
    'code' => 'required|max:11|regex:/[^#]*/',
]);

but it doesn't work; if I wrote for example "CG#777" it accept the string, but I want it to discard.

Anyone can help me?

3

There are 3 best solutions below

0
Hilmi Hidayat On BEST ANSWER

Try this one

$request->validate([
    'code' => 'required|string|max:11|regex:/^[^#]+$/'
]);
1
agodoo On

I found the right solution with the following regex:

^[^#]+$
0
Flame On

It can be somewhat "simplified" (depending on your definition) by only using a single validation rule like so:

^[^#]{1,11}$

The ^ negates the matching options (so [^#] matches everything but the #), while {1,11} requires 1 to 11 characters.

The ^ and $ are delimiters for the start and end of a string (may i recommend https://regex101.com/ for testing out your regexes).

This means you can leave out the required and max:11 rules, however it might still be nice to have them for validation messages.