-1

I am using this regex to make sure that names can only contain letters, apostrophe or hyphen.

Validator::extend('people_names', function($attribute, $value, $parameters, $validator) {
        return preg_match("^[a-zA-Z-'\s]+$^", $value);

When I use this tool to check if the regex is correct, it shows its correct, but in my form when I test an input starting with digits or any other characters like 123name or #$#$name it passes while it should not. An input with letters then digits like name123 is rejected.

Phillis Peters
  • 2,232
  • 3
  • 19
  • 40
  • [Falsehoods Programmers Believe About Names](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/) – Thomas Ayoub Sep 15 '16 at 08:28

2 Answers2

2

The PHP preg_ functions need to start with /^ and end with $/.

Try this:

preg_match("/^[a-zA-Z-'\s]+$/", $value);
Patrick Mlr
  • 2,955
  • 2
  • 16
  • 25
1

In your regex ^[a-zA-Z-'\s]+$^, you are only checking if the string ends with a letter by using the $ at the end, but the ^ at the beginning is used here asthe regex delimiter, since it's also at the end.

I'd recommend using another string delimiter, such as # or / :

preg_match("#^[a-zA-Z-'\s]+$#", $value) should work.

roberto06
  • 3,844
  • 1
  • 18
  • 29