Reputation:
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
Reputation: 7719
I have a feeling that, given the question, it is best to keep the solution simple.
Note this observations:
"a" < "b"
and "A" < "B"
are both true."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?
Upvotes: 0
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