开发者

javascript validation for numbers

开发者 https://www.devze.com 2023-03-10 12:22 出处:网络
can someone tell me what i am doing wrong here.. i am not getting invalid number alert when i enter 1 1 0r a

can someone tell me what i am doing wrong here.. i am not getting invalid number alert when i enter 1 1 0r a

function validateNumeric() {
  var old_val = document.getElementById("tbNumber").value;
  var new_val = old_val.replace(/^\s+|\s+$/g,"");
  var validChars = '0123456789.'; 

  for(var i = 0; i < val.lengt开发者_运维问答h; i++){ 
    if(validChars.indexOf(new_val.charAt(i)) == -1){
      alert('Please enter valid number');
      return false; 
    } else {
        document.getElementById("tbNumber").value = new_val;
      }
  }
  return true; 
}


In your for loop test, you're referencing a variable val, which probably comes back as having a length of 0, so your loop will never do anything and the function will simply return true. I'm guessing your for loop should actually look like:

for(var i = 0; i < new_val.length; i++){
    ...
}


There is a much simpler solution: use a regular expression.

Your valid characters are the digits 0 -9, including a decimal point, correct? Well, the RegEx for that is \d. Therefore, this would check if the value entered is numeric:

(/\d/).test( myValue );

Therefore, your code just needs to use the RegEx instead of an expensive loop.

function validateNumeric(){
    var x = document.getElementById('foo');
    var y = x.value.replace(/^\s+|\s+$/g,'');
    var DIGITS = (/\d/); // Uppercase because this is a constant value

    if (!DIGITS.test( y )){
        alert('Please enter a valid number.');
        return false;
    } else {
        x.value = y;
        return true;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号