views:

110

answers:

5

Hello I am very naive with regular expressions and I wasn't really able to find what I need.

For website validation purposes, I need first name and last name validation.

For first name it should only contain letters and can be several words with space and no letters and as minimum 3 characters and at top 30 characters. Empty string shouldnt be validated. Ie:

Jason, jason, jason smith, jason smith , JASON, Jason smith, jason Smith, jason SMITH

For the last name, it should be a single word, only letters and with at least 3 characters and at top 30 characers. Empty string shouldnt be validated. IE: lazslo, Lazslo, LAZSLO

I will be greatful for any help.

+1  A: 

First name would be

"([a-zA-Z]{3,30}\s*)+"

If you need the whole first name part to be shorter than 30 letters, you need to check that seperately, I think. The expression ".{3,30}" should do that.

Your last name requirements would translate into

"[a-zA-Z]{3,30}"

but you should check these. There are plenty of last names containing spaces.

Jens
A: 
var name = document.getElementById('login_name').value; 
if ( name.length < 4  && name.legth > 30 )  
{
    alert ( 'Name length is mismatch ' ) ;
} 


var pattern = new RegExp("^[a-z\.0-9 ]+$");
var return_value = var pattern.exec(name);
if ( return_value == null )
{
    alert ( "Please give valid Name");
    return false; 
} 
pavun_cool
+1  A: 

If you want the whole first name to be between 3 and 30 characters with no restrictions on individual words, try this :

[a-zA-Z ]{3,30}

Beware that it excludes all foreign letters as é,è,à,ï.

If you want the limit of 3 to 30 characters to apply to each individual word, Jens regexp will do the job.

Thibault Falise
+1  A: 

You make false assumptions on the format of first and last name. It is probably better not to validate the name at all, apart from checking that it is empty.

Sjoerd
`/^[Ss]joerd$/`
macek
+2  A: 

Don't forget about names like:

  • Mathias d'Arras
  • Martin Luther King, Jr.
  • Hector Sausage-Hausen

This should do the trick for most things:

/^[a-z ,.'-]+$/i

OR Support international names with super sweet unicode:

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

macek