2

I am trying to use regex to validate the users first and last name on a form.

Rules

  • Must be alphabetic
  • First letter can either by uppercase or lowercase
  • Followed by all lowercase letters
  • Must be at least 2 letters long and cannot be longer than 15 letters.
  • No spaces.

This is my attempt at the regular expression

!preg_match('/^[a-Z]{1}[a-z]{1,14}$/' 

But I am getting the error:

: preg_match(): Compilation failed: range out of order in character class at offset 4

Zestyy99
  • 287
  • 2
  • 10
  • `[a-Z]` -> `[a-zA-Z]` – RomanPerekhrest Mar 19 '18 at 12:41
  • `[a-Z]` is an empty range because `Z` is before `a` in the ASCII chart. Actually, this is what the error message tries to tell you. – axiac Mar 19 '18 at 12:41
  • Do you mean `[a-z]` not `[a-Z]`? Or even [a-zA-Z]? You might want to also consider people called Princess Consuela Bananahammock. – Zoe Edwards Mar 19 '18 at 12:41
  • `{1}` is a no-op. You can remove it and the meaning of the `regex` doesn't change. – axiac Mar 19 '18 at 12:43
  • ^([A-z][A-Za-z]*\s*[A-Za-z]*)$ – Tehseen Ahmed Mar 19 '18 at 12:44
  • 2
    @TehseenAhmed the `regex` you suggest doesn't follow any of the rules listed in the question. – axiac Mar 19 '18 at 12:45
  • @axiac for first and last name – Tehseen Ahmed Mar 19 '18 at 12:47
  • @TehseenAhmed btw, `[A-z]` includes six non-letter characters: `[`, `\ `, `]`, `^`, `_` and `\``. – axiac Mar 19 '18 at 12:49
  • i know but the rule was was not broken – Tehseen Ahmed Mar 19 '18 at 12:53
  • 1
    @Zestyy99 It is true, `[a-Z]` matches any character that lies **after** `a` and **before** `Z` (including these two characters). The trouble is that `Z` comes before `a` in the [ASCII table](https://en.wikipedia.org/wiki/ASCII) and consequently, `[a-Z]` is an empty range (and invalid, as the error message reports). – axiac Mar 19 '18 at 12:55
  • 1
    Read about [regular expressions in PHP](http://php.net/manual/en/reference.pcre.pattern.syntax.php) and use https://regex101.com to validate your expressions (and learn how they match). – axiac Mar 19 '18 at 12:56

1 Answers1

3

a-Z isn't a valid range, you need to change this to include both uppercase and lowercase ranges.

change to this: ^[a-zA-Z][a-z]{1,14}$

Juakali92
  • 1,155
  • 8
  • 20