简体   繁体   English

Html 和 javascript 输入验证

[英]Html and javascript input validation

I am trying to have my input only accept Numbers and the '.', it is working great but it doesn't allow for number pad number keys.我试图让我的输入只接受数字和“.”,它工作得很好,但它不允许使用数字键盘数字键。 I cant seem to find the exact answer online.我似乎无法在网上找到确切的答案。

HTML HTML

<input type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#" onkeypress="return isNumeric(event)" onkeydown="return keyispressed(event);">

JavaScript JavaScript

//prevent , and $ from being input
function keyispressed(e){
    var charval= String.fromCharCode(e.keyCode);
    if(isNaN(charval) && (e.which != 8 ) && (e.which != 190 )){
        return false;
    }
    return true;
}


//is input numeric
function isNumeric (evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode (key);
  var regex = /[0-9]|\./;
  if ( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

Thanks for the help!谢谢您的帮助!

The best way I believe would be to add a class to all the inputs that only allow numbers.我认为最好的方法是为所有只允许数字的输入添加一个类。 Then you can restrict any input that doesn't match the pattern or a number/decimal.然后您可以限制任何与模式或数字/小数不匹配的输入。

 function numberVerfication(value) { var pattern=/^[0-9]*(\\.)?[0-9]*$/; if (value.match(pattern) != null){ return value } else { var p=/[0-9]*(\\.)?[0-9]*/; return value.match(p)[0]; } } $('.numbersOnly').keyup(function(e) { e.target.value = numberVerfication(e.target.value); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input class='numbersOnly' type="text" id="ItemTotal#i#" name="ItemTotal#i#" value="#qPriceAct#">

Simple using REGEXP简单使用REGEXP

HTML HTML

<input type="text" class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct">

JQUERY查询

$('.numbersOnly').keyup(function (e) {
    this.value = this.value.replace(/[^0-9\.]/g, '');
});

JAVA SCRIPT爪哇脚本

function numValidate(that){
  that.value = that.value.replace(/[^0-9\.]/g, '');  
}

<input type="text" onkeypress='numValidate(this)' onkeyup='numValidate(this)' class='numbersOnly' id="ItemTotali" name="ItemTotal#i" value="qPriceAct"/>

Demo演示

 function numberVerfication(value){ return value.replace(/[^0-9.\\-+]/g, ''); } $('.numbersOnly').keyup(function(e){ e.target.value=numberVerfication(e.target.value); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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