4

I have this validation:

'users.first_name' => 'required|min:2|regex:/[A-Za-z. -]/|max:255',

Why this validation pass this name: John[][]

2 Answers2

11

Someone in comments also pointed to this issue that by /[A-Za-z. -]/ you don't care about all characters but saying that's enough for me if field under validation has only the least of that characters.

To have only those characters you should specify beginning and ending of the input text by using a caret ^ and $:

regex:/^[A-Za-z. -]+$/
revo
  • 47,783
  • 14
  • 74
  • 117
  • 2
    Thanks for this answer. I had similar requirements for a username minus allowing the space character and I needed to allow numbers. So all usernames can have numbers, letters a-z both upper and lowercase, underscores, dots and dashes. This works for Laravel 5.4, here's the end result : `'username' => ['required', 'regex:/^[0-9A-Za-z.\-_]+$/', 'max:150'],` – racl101 May 15 '17 at 22:56
  • Thank you @racl101. It still works on Laravel 7. In my case I declared a `Rule` class and used your regex there. Also I considered appropriate adding `'min:3'`. – JCarlosR Sep 10 '20 at 23:05
2

use Alpha dash validation

'users.first_name' => 'required|min:2|alpha_dash|max:255',
Abhishek
  • 3,900
  • 21
  • 42