Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript regex valid name

I want to make a JavaScript regular expression that checks for valid names.

  • minimum 2 chars (space can't count)
  • space en some special chars allowed (éàëä...)

I know how to write some seperatly but not combined.

If I use /^([A-Za-z éàë]{2,40})$/, the user could input 2 spaces as a name

If I use /^([A-Za-z]{2,40}[ éàë]{0,40})$/, the user must use 2 letters first and after using space or special char, can't use letters again.

Searched around a bit, but hard to formulate search string for my problem. Any ideas?

like image 680
user1232673 Avatar asked Nov 30 '22 15:11

user1232673


1 Answers

Please, please pretty please, don't do this. You will only end up upsetting people by telling them their name is not valid. Several examples of surnames that would be rejected by your scheme: O'Neill, Sørensen, Юдович, . Trying to cover all these cases and more is doomed to failure.

Just do something like this:

  • strip leading and trailing blanks
  • collapse consecutive blanks into one space
  • check if the result is not empty

In JavaScript, that would look like:

name = name.replace(/^\s+/, "").replace(/\s+$/, "").replace(/\s+/, " ");
if (name == "") {
  // show error
} else {
  // valid: maybe put trimmed name back into form
}
like image 163
Thomas Avatar answered Dec 06 '22 09:12

Thomas