如何验证只有 2 位数字的输入数字并允许用户使用 JQuery 输入点数字?
用户可以输入0到99个数字和点数
如 (
0.1(3位数)
3.14(4位数)
98.121212121786234435243(更多位数)
等等......)
https://jsfiddle.net/kwcft9bq/
<!DOCTYPE html>
<html>
<body>
<form id="submit_form" method="post">
<input type='number' id="name" name='number' min="0" required><br>
<input type="submit" text="Submit" >
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
<script>
$(document).on('input', "#number", function () {
if ($(this).val().length > 2) {
$(this).val($(this).val().slice(0, 2));
}
});
</script>
</body>
</html>
我尝试使用
if($(this).val() == "0." || $(this).val() == "1." .....|| $(this).val() == "98."){
//can input more digits after "points" -> .
}
但最终不起作用
任何的想法???谢谢
您可以使用正则表达式来验证该模式:
$(document).on('input', "#number", function() {
var regex = /^\d{0,2}(\.\d+)?$/;
var value = $(this).val();
if (!regex.test(value)) {
$(this).val(parseFloat(value.slice(0, 2) + "." + value.slice(2)));
}
});
你可以在这里查看
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句