View Full Version : Validating a entry (first name last)

03-21-2009, 10:51 PM
This is driving me bonkers. I want the user to enter the first and last name in a text field, it will only accept the entry is there are no spaces at the end or begining of the entry and at least one in the middle. This was tricky as I'm a newb, but then I added the part that makes sure only letters were added (supposed to be the easy part) and the whole thing went kerplunk, I know there's a conflict somewhere, just not knowlageable enough to figure out where, can any one help? :confused:

Here's my code:

function nm(){
var name = document.getElementById('text').value;
var leng = name.length - 1;

if(name == "" || name.indexOf(" ") == 0 || name.lastIndexOf(" ") == leng || name.match(" ") == null || name.match(/[^a-zA-Z]/)) {

alert('enter a first and a last name');
document.getElementById("name").innerHTML = name;

Like I said, everything worked fine until I added the name.match[^a-zA-z] bit. Thanks in advance for any help yo!

03-21-2009, 11:21 PM
You forgot about the space between name and surname:


Philip M
03-21-2009, 11:34 PM
Why not simply strip leading and trailing spaces?

x = x.replace(/^\s+|\s+$/g,"");

Also note that in Internet Explorer, names and IDs are global variables and thus you should NEVER use a global variable or function name which is the same as an HTML element name or ID. You should also avoid giving names or id's to your variables/functions/arguments/forms words which are JavaScript methods/properties/attributes such as 'name' or 'id' or 'value' or 'text' or 'checked' or 'submit' or 'replace' or 'button' or 'radio' or 'parseInt'. And of course you may not give a variable a name which is a Javascript keyword or event such as alert, case, char, false, int, onload, return, this, void, and so on.

03-21-2009, 11:58 PM
Thanks! One of the things I love about looking over these boards is different approaches to the same problem, I didn't think of this LOL duh! Great tip!!!

03-22-2009, 12:00 AM
Worked like a charm!! thanks!

Philip M
03-22-2009, 11:09 AM
Your heading Validating a entry (first name last) suggests you want to reverse the order of first and last names. This will do that for you:-

str = "John Smith"
str = str.replace(/(\S+)\s+(\S+)/,"$2 $1");
alert (str);

As well as leading and trailing spaces you may wish to strip out non-alpha characters:-

str = str.replace(/[^a-z-']/gi,""); // retain hyphen and apostrophe for Peter O'Toole and John Smith-Jones