I’m running some functions to verify that the user-entered text in a form contains at least one number and letter. It doesn’t seem to be working. Since the two functions are nearly identical, I’ll just post one of them:
function hasALetter(textField){
//returns true or false based on whether or not the text field has at least one letter inside it
console.log("Checking for letters...");
var hasLetter = false;
for(var i=0, checkLength=textField.length; i<checkLength; i++){
var letter = textField.substr(i,1);
console.log("letter = " + letter);
if(isNan(letter) == false){
hasLetter = false;
}
}
if(hasLetter == true){
return true;
}
}
The log (“letter = ” + letter) never shows up in my console. I’m probably missing something silly, but it doesn’t seem to be completing the function.
For reference, here is how I’m calling the functions:
if(pwd.value.length > 9){
var pwdLetter = hasALetter(pwd);
var pwdNumber = hasADigit(pwd);
if(pwdLetter==true){
if(pwdNumber==true){
Yes, I’m aware that it’s very messy, but I’m still learning. I’m sure there’s more advanced/cleaner ways of doing this validation, but for the purposes of my schooling, I’m doing it like this for now.
The easiest way to check if a string has a letter is the Regular Expression:
If you want to loop through the string and also want to use the
isNaNfunction, this would do:But I would not recommend this method, because
isNaNchecks whether the first argument is a number or not. First of all, not all characters that aren’t numbers are letters. Secondly, the argument you pass in is a string (str[i]returns a character of type string, even if it is a digit)