Regex to validate names

前端 未结 6 1830
一个人的身影
一个人的身影 2021-01-19 12:04

I would like to create a regex which validates a name of a person. These should be allowed:

  • Letters (uppercase and lowercase)
  • -
6条回答
  •  Happy的楠姐
    2021-01-19 12:34

    I had the same problem. First I came up with something like

        preg_match("/^[a-zA-Z]{1,}([\s-]*[a-zA-Z\s\'-]*)$/", $name))
    

    but then realized that UTF-8 chars of countries like Sweden, China etc. for example Õ å would not be allowed which was important to my site since it's an international site and don't want to force users not being able to enter their real name.

    I though it might be an easier solution instead of trying to figure out how to allow names like O'Malley and Brooks-Schneider and Õsmar (made that one up :) to rather catch chars that you don't want them to enter. For me it was basically to avoid xss JS code being entered. So I use the following regex to filter out all chars that might be harmful.

        preg_match("/[~!@#\$%\^&\*\(\)=\+\|\[\]\{\};\\:\",\.\<\>\?\/]+/", $name)
    

    That way they can enter any name they want except chars that really aren't part of any name. Hope this might be useful.

提交回复
热议问题