Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript surname validation with regex

I need to write validation for surname with polish letters.

I wrote something like this:

"^[A-Z][\u0000-\u007F\u0100-\u017F]+([ |-][A-Z][\u0000-\u007F\u0100-\u017F])*$"

where:

  • [A-Z]: the first letter must be capital
  • [\u0000-\u007F\u0100-\u017F]+: other letters
  • ([ |-][A-Z][\u0000-\u007F\u0100-\u017F])*: space for optional second part of surname with a "-" or space

Everything is fine, but when I type for example:

"Matt...;'"

I still have a match. How can I "cut" symbols like dots . and quotation marks?

like image 781
FilipW Avatar asked Jun 02 '26 03:06

FilipW


1 Answers

It seems you may use

^[A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ][a-pr-uwy-ząćęłńóśźż]+(?:\s[A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ][a-pr-uwy-ząćęłńóśźż]+)?\s[A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ][a-pr-uwy-ząćęłńóśźż]+(?:-[A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ][a-pr-uwy-ząćęłńóśźż]+)?$

See the regex demo.

It is based on all Polish alphabet letters regex (that excludes V/v, Q/q and X/x from the ASCII letter range) and will match names that:

  • Matches a first name
  • Then may match an optional second first name (after a whitespace)
  • A surname
  • An optional surname part after a hyphen.

Details

  • ^ - start of string
  • [A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ][a-pr-uwy-ząćęłńóśźż]+ - an uppercase Polish letter and 1+ lowercase ones
  • (?:\s[A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ][a-pr-uwy-ząćęłńóśźż]+)? - 1 or 0 occurrences of a whitespace and then an uppercase Polish letter and 1+ lowercase ones
  • \s - a single whitespace char
  • [A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ][a-pr-uwy-ząćęłńóśźż]+ - an uppercase Polish letter and 1+ lowercase ones
  • (?:-[A-PR-UWY-ZĄĆĘŁŃÓŚŹŻ][a-pr-uwy-ząćęłńóśźż]+)? - 1 or 0 occurrences of a hyphen and then an uppercase Polish letter and 1+ lowercase ones
  • $ - end of string.

If you plan to support x, q and v in the names, replace a-pr-uwy-z with a-z and A-PR-UWY-Z with A-Z.

like image 127
Wiktor Stribiżew Avatar answered Jun 05 '26 00:06

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!