[英]Regular expression to restrict 'n' digits before and after decimal point
I need a regex for restrict 10 digits before decimal and 2 digits after decimal point.我需要一个正则表达式来限制小数点前 10 位和小数点后 2 位。 i have tried with this
我试过这个
if (!(/^\d{1,10}(\.$|\.\d{1,2}$|$)/).test(value)) {
event.preventDefault();
event.stopPropagation();
}
<input id="input" type="number" />
It is working fine for input type text .But it is not working for type number.它适用于输入类型text 。但它不适用于类型 number。
Please help me on this请帮我解决这个问题
This should work. 这应该工作。
if(! (/^[0-9]{10}\.[0-9]{2}$/).test(1234567890.12)) {
}
Just use this regex /^[0-9]{10}\\.[0-9]{2}$/
in your code to verify if value is 10 digits before decimal and 2 after. 只需在您的代码中使用此正则表达式
/^[0-9]{10}\\.[0-9]{2}$/
来验证值是否为小数点前的10位数字和小数点后的2位数字。
Parameters 参量
oninput
: Detect immediate changes to the input
tag. oninput
:检测对input
标签的立即更改。 max
: Set the maximum value. max
:设置最大值。 min
: Set the minimum value. min
:设置最小值。 type
: Set what type of input
tag you want. type
:设置所需的input
标签类型。 value
: Set the current value. value
:设置当前值。 step
: Set the amount to ascend or descend by. step
:设置上升或下降的量。 //(function(object){object.value=parseFloat(object.value).toFixed(2);})(this) //(function(object){var val=object.value;object.value=val.slice(0,val.indexOf('.')+3);})(this)
<input id="input" oninput="(function(object){object.value=parseFloat(object.value).toFixed(2);})(this)" type="number" value="0.00" step="0.01" min="0.00" max="9999999999.99" />
To restrict Decimal places before and after decimal this should work: 要限制小数点之前和之后的小数位,这应该起作用:
function ValidateDecimalInputs(e) { var beforeDecimal =3; var afterDecimal = 2; $('#'+e.id).on('input', function () { this.value = this.value .replace(/[^\\d.]/g, '') .replace(new RegExp("(^[\\\\d]{" + beforeDecimal + "})[\\\\d]", "g"), '$1') .replace(/(\\..*)\\./g, '$1') .replace(new RegExp("(\\\\.[\\\\d]{" + afterDecimal + "}).", "g"), '$1'); }); }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="text" id = "textBox" onclick="ValidateDecimalInputs(this)"/>
value= (value.substr(0, value.indexOf(".")) + value.substr(value.indexOf("."), 2));
this will work as it will give all values before "."这将起作用,因为它将在“。”之前给出所有值。 and only 2 values after "."
并且“.”之后只有 2 个值
This worked for me, even with number type.这对我有用,即使是数字类型。
JQuery查询
$("body").on("keyup", ".patternCheck", function(){
if(this.value.match(/^[0-9]{1,10}[.]{1}[0-9]{1,2}$/) == null)
{
$(this).val($(this).attr("pval"));
}
else
{
$(this).attr("pval", $(this).val());
}
});
HTML HTML
<input type="number" value="0.0" pval="0.0" class="patternCheck">
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.