jQuery输入掩码小数点
我正在使用 https://github.com/RobinHerbots/jquery.inputmask ,但我似乎无法导出与整数&相对应的模式.十进制.例如
I am using the jQuery plugin found at https://github.com/RobinHerbots/jquery.inputmask but I can't seem to be able to derive a pattern that corresponds to a integer & a decimal. For example,
我需要以下内容有效:
10
150
12.25
0.45
此刻我正在做
$('#from_id').inputmask("9{0,5}.9{0,2}");
但这意味着如果用户未指定小数点后的内容,则输出为:
But this means that if the user does not specify what comes after the decimal point, the resulting output is:
例如,如果用户只想输入12(并且他没有指定小数点),则输出为
For example, if the user only wants to input 12 (and he does not specify the decimal point) the output is
12___.__
(因为掩码正在等待小数点)
(as the mask is waiting for the decimal point)
但是,如果用户指定小数点,例如12.00,则输出如下所示:
But if the user specifies the decimal point, for example 12.00, The output is fine like:
12.00
有人可以帮助我解决这个问题吗?
Could someone help me with this problem?
尝试使用可选的parmaneter greedy
之类的
Try to use the optional parmaneter greedy
like,
$('#from_id').inputmask({'mask':"9{0,5}.9{0,2}", greedy: false});
阅读 optional-masks-with-greedy-false
您可以验证上述遮罩.或使用您自己的逻辑来进行验证,
You can validate above mask. Or use your own logica to validate like,
$(function(){
$('#id').on('keyup', function(e) {
if (!this.value.match(/^\d{0,5}(\.[0-9]{1,2})?$/)) {
$(this).addClass('error');// adding error class
} else {
$(this).removeClass('error');// remove error class
}
});
});
或者只需使用 toggleClass 之类的
$(function() {
$('#id').on('keyup', function(e) {
$(this).toggleClass('error', !this.value.match(/^\d{0,5}(\.[0-9]{1,2})?$/));
});
});
.error {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="id" />