1

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.length; 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; 
}
3
  • Duplicate stackoverflow.com/questions/6228041/javascript-check-for-spaces ? Commented Jun 3, 2011 at 19:08
  • what was wrong with the top answer when you asked this before? Commented Jun 3, 2011 at 19:13
  • i don't think it is a duplicate - see my answer. Commented Jun 3, 2011 at 19:15

2 Answers 2

2

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++){
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

0

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;
    }
}

1 Comment

thanx for the help but if someone enter 2..2 than how can i test that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.