Rpant
Rpant

Reputation: 1054

Javascript to validate a name field

I am using java script patterns to validate a name , but realized I really need to be an expert at patterns to solve this problem. The function should return true for a name that is made of alphabets, a name can be made of one or more alpha words that are seperated by white space or hyphen Eg. following are valid names.

  1. John Fisher
  2. John Andrew Fisher
  3. Micheal B Jackson
  4. Micheal-B-Jackson

Micheal Micheal-B-Jackson-Fisher

Following are invalid names

  1. micheal B jackson (Assume there is whitespace after jackson)
  2. micheal ( assume there is a whitespace before m)
  3. Micheal/ ( this one has non alpha char)
  4. -micheal-B-Jackson ( starts with a hyphen )
  5. micheal*jackson ( has a * words , words can be seperated only by - or whitespace)

I had written the following function which worked fine as long as the name is not made of more than 2 words seperated by whitespace or - . However the requirements have now changed and the name can have more than one words.

function isAlpha(field) {
    var lbl = field.name;
    var val = field.value;
    if (val==null || val.length==0) return true;

    //egs of this pattern 1)Rachit Pant 2)R Pant
    var rep1 = /[A-Za-z]+\s[A-Za-z]+/;
    //egs of this pattern 1)Rachit-Pant 2)R-Pant
    var rep2 = /[A-Za-z]+[-][A-Za-z]+/;
    //one or more alpha character
    var rep3 = /[A-Za-z]+/;

    var test1 = val.match(rep1);
    var test2 = val.match(rep2);
    var test3 = val.match(rep3);
    if((test1!=null)){      
        if(test1.length == 1 && test1[0].length == val.length)
            return true;        
    }
    if((test2!=null)){      
        if(test2.length == 1 && test2[0].length == val.length)
            return true;        
    }

    if((test3!=null)){      
        if(test3.length == 1 && test3[0].length == val.length)
            return true;    
    }

    alertMe('GL006',field,field);
    return false;

}

Upvotes: 0

Views: 159

Answers (1)

berrunder
berrunder

Reputation: 140

Try this regexp: ^[a-zA-Z]+(?:[ -][a-zA-Z]+)*$. And about your javascript code: you don't need to use match function, test is enough, like this:

var regExp = /^[a-zA-Z]+(?:[ -][a-zA-Z]+)*$/;
return regExp.test(val);

Upvotes: 1

Related Questions