user2205909
user2205909

Reputation:

Validate First and Last name (not using regular expression)

I need to validate user input of first and last name in the one input box. I have to make sure they only use letters and no other characters and is in uppercase or lowercase ex.. John Smith. I can find a lot of ways to do this using regular expressions, but the task has specifically asked that no regular expressions be used.

Even if someone to point me to where I can find this information myself.

Thanks

Upvotes: 0

Views: 382

Answers (2)

user2246674
user2246674

Reputation: 7719

I have a feeling that, given the question, it is best to keep the solution simple.

Note this observations:

  1. A string can be indexed like an array and has a length like an array. Thus, a string can be looped like an array.
  2. Strings are lexically ordered. That is, "a" < "b" and "A" < "B" are both true.
  3. String.toLower can translate "A" to "a"

Then we can start a basic C-style approach:

for (var i = 0; i < inp.lenth; i++) {
   var ch = inp[ch];
   if (ch == " ") ..              // is space
   if (ch >= "a" && ch <= "z") .. // lowercase English letter
   ..

Of course, the problem may be more than simply ensuring that the letters are all in { a-z, A-Z, space}. Consider these inputs - are they valid?

  • "John Doe"
  • "JohnDoe"
  • " John "

Upvotes: 0

dave
dave

Reputation: 64657

Just check each letter to see if it's valid. So you create an array of valid characters, then make sure each character is in that array.

function validate_name(name) {
  var alphabet = 'abcdefghijklmnopqrstuvwxyz';
  alphabet = alphabet + ' ' + alphabet.toUpperCase();
  alphabet = alphabet.split(''); //turn it into an array of letters.
  for (i=0; i<name.length; i++) {
    if (!~alphabet.indexOf(name.charAt(i)) { //!~ just turns -1 into true
       return false;
    }
  }

  return true;
}

Upvotes: 1

Related Questions