开发者

regex for a full name

开发者 https://www.devze.com 2023-03-27 04:41 出处:网络
I\'ve recently been receiving a lot of first name only entries in a f开发者_StackOverfloworm.While maybe I should have had 2 separate first and last name fields this always seemed to me a bit much.But

I've recently been receiving a lot of first name only entries in a f开发者_StackOverfloworm. While maybe I should have had 2 separate first and last name fields this always seemed to me a bit much. But I would like to try and get a full name which basically can only be determined by having at least one space.

I came up with this, but I'm wondering if someone has a better and possibly simpler solution?

/([a-zA-ZàáâäãåèéêëìíîïòóôöõøùúûüÿýñçčšžÀÁÂÄÃÅÈÉÊËÌÍÎÏÒÓÔÖÕØÙÚÛÜŸÝÑßÇŒÆČŠŽ∂ð,.'-]{2,}) ([a-zA-ZàáâäãåèéêëìíîïòóôöõøùúûüÿýñçčšžÀÁÂÄÃÅÈÉÊËÌÍÎÏÒÓÔÖÕØÙÚÛÜŸÝÑßÇŒÆČŠŽ∂ð,.'-]{2,})/

This is basically this /([a-zA-Z,.'-]) ([a-zA-Z,.'-])/ plus unicode support.


I'd first make sure that you really do need people to give you a last name. Is that a genuine requirement? If not, I'd skip it because it adds unnecessary complication and barriers to entry. If it really IS a requirement, it probably makes sense to have separate first and last name fields in your UI so that it's explicit.

The fact that you didn't do that to begin with suggests that you might not really need the last name as much as you think you do.

To answer your original question, this expression might give you what you're looking for without the guesswork:

/[\w]+([\s]+[\w]+){1}+/

It checks that the string contains at least 2 words separated by whitespace. Like Tim Pietzcker pointed out, validating the words themselves is prone to error.


In Ruby 1.9, you have access to Unicode properties (\p{L} is a Unicode letter). But trying to validate a name in any way (regex or not) is prone to failure because names are not what you think they are.

Your theory that "if there's a space, there must be a last name there" is incorrect, too - think of first and middle names...

0

精彩评论

暂无评论...
验证码 换一张
取 消