开发者

Javascript onclick form validation

Can someone tell me what I am doing wron开发者_StackOverflow中文版g over here.. Its printing out alert when I put character like abc but when I have valid number its not saving...

function ValidateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var validChars = '0123456789.'; 

    for(var i = 0; i < val.length; i++) { 
      if(validChars.indexOf(val.charAt(i)) == -1)
       alert('Please enter valid number');
       return false; 
        } 

        return true; 
    }

<INPUT TYPE=SUBMIT NAME="action" VALUE="Save Changes" onclick="return ValidateNumeric();" >


Pay attention to the statement start and end - the "return false;" will terminate the "for" loop on the first iteration.

Correct code:

function ValidateNumeric() {
  var val = document.getElementById("tbNumber").value;
  var validChars = '0123456789.'; 

  for(var i = 0; i < val.length; i++) { 
    if(validChars.indexOf(val.charAt(i)) == -1) {
      alert('Please enter valid number');
      return false;
    }
  } 

  return true; 
}


format your if correctly, else it will consider only first statement.

 for(var i = 0; i < val.length; i++) { 
      if(validChars.indexOf(val.charAt(i)) == -1)
       {
        alert('Please enter valid number');
        return false; 
       }
    } 


Use regular expressions!

function validateNumeric() {
    var val = document.getElementById("tbNumber").value;
    var regex = /^[0-9\.]+$/;

    if(regex.test(value))
        return true
    else {
        alert("Please enter a valid number");
        return false;
    }
}

However, that regex allows 1.22.3.6...2 as an input, which is probably not desired. You probably want to have the regex ^(\d+(\.\d+)?|\.\d+)$

Also, HTML tags should be lower case, and attributes should be quoted:

<input type="number" id="tbNumber" />
<input type="submit" name="action" value="Save Changes" onclick="return validateNumeric();"  />
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜