简体   繁体   中英

Validating input type numbers using javascript / jQuery

  • I have a input box and need to accept just numbers.

  • I use javascript and it works fine but the problem : when the box is empty or deleting numbers it returns false and the box color get red.

Here is the codes:

<input id="amount" type="number" size="7" name="amount" onkeypress='return isNumberKey(event)' required/>


<script type="text/javascript">
    function isNumberKey(evt){
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (charCode > 31 && (charCode < 48 || charCode > 57))
            return false;
        return true;
    }
</script>

check it this validation code : http://jsbin.com/ImIruPEf/1/edit

$(document).ready(function(){
  $("#Submit").click(function(e){
     var isNumber =   IsNumberOnly('input#Age');
    if(!isNumber)
    {
      e.preventDefault();
      $("#ErrorMessage").text('Invalid value. Please enter numeric value.');
    }
    else
    {
       $("#ErrorMessage").text('Success.');
    }
  });
});

function IsNumberOnly(element) {    
    var value = $(element).val();
    var regExp = "^\\d+$";
    return value.match(regExp); 
}
<script type="text/javascript">
function demoMatchClick() {
 var re = new RegExp("^[0-9]+$");
 var val=document.GetelementByID("amount").value;
   if (val.match(re)) {
      alert("Successful match");return true;
   } else {
      alert("No match"); return false;
   }
 }
 </script>

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