简体   繁体   中英

PHP+HTML - Regex to deal with names

I would like to create a regex to validate customer names.

This would be a name like Peter, André, Mary-Anne or Van Rensberg. Asian characters should not be allowed, along with other characters that do not relate to names of this manner.

This will be validated via the HTML5 pattern attribute and then again via PHP as a last resort.

I originally started off with this: [^\\p{L}\\s0-9]{1,120} which almost applies that I have had in mind, but does not relate exactly to what I am trying to accomplish.

It will basically allow characters like c or é or -, but will not allow spaces and as a side affect allows the input of other special characters like / and %.

Given my very limited knowledge on this subject I thought I would ask this question in order to gain some knowledge from some people that know more than I do.

Thank you for any suggestions of feedback in this regard!

You should start with:

/^([\\p{Letter}\\p{Latin}]+(\\-[\\p{Letter}\\p{Latin}]+|[\\x20\\xA0\\x{0020}\\x{00A0}])?)+$/

and if needed, you can add other scripts, such as:

\\p{Hebrew} , \\p{Cyrillic} , \\p{Georgian} , \\p{Greek} , etc.

For more information check " Unicode Regular Expressions ".

I suggest you to trim leading/trailing whitespace characters before regex validation .

if you are going to validate if a name is a name, you should try to validate if that name isn't an invalid string with spaces only or a string with a really short lenght. if you were expecting a regex to validate names maybe this should work

/(^|\s)[A-Za-z\-áéíóúÁÉÍÓÚ]+($|\s)/i

but I insist that the better thing that you can do is to make sure that the name isn't an invalid string, because there is a lot of name and last name with many shapes

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM