简体   繁体   中英

textbox must contain number or letter validation on javascript without regex

Hi guys i got a problem here, how i can validate a password box that must contain at least one numeric character. i'm not allowed using regular expression / regex. i have tried searching over the web, but the solution is always end with regex.

here's my code that i try

function validateIn()
{
var pass=document.getElementById('password').value;
for(var i=0;i<pass.length;i++)
{
    if(isNaN(pass.charAt(i))==false)
    {
        return true;
        break;
    }
    else
    {
        return false;
    }
}
}

i have tried that way but i fail, can u help me guys? thanks before

One possible approach:

function validateIn() {
  var pass = document.getElementById('password').value,
      p    = pass.length,
      ch   = ''; 

  while (p--) {
    ch = pass.charAt(p);
    if (ch >= '0' && ch <= '9') {
      return true; // we have found a digit here
    }
  }
  return false; // the loop is done, yet we didn't find any digit
}

The point is, you don't have to return immediately after you have found a normal character (as you're basically looking for a single digit) - you just have to move on with your checking.

Note that I have gone without isNaN , as it's a bit inefficient: the only thing required is a range check.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM