如何使用Jquery在Decimal值中验证以下内容?
我已经创建了基本小提琴,我可以验证号码。
我不允许用户输入除数字,点(。)或逗号(,)(可互换)以外的任何内容,退格
HTML
<input type="text" class="myTexbox" />
JQUERY
$(document).ready(function () {
$('.myTexbox').keypress(function (event) {
return isDecimalNumber(event, this)
});
});
function isDecimalNumber(eve, element) {
var charCode = (eve.which) ? eve.which : event.keyCode
if (
(charCode != 8) //For Backspace Active
&&
(charCode != 44 || $(element).val().indexOf(',') != -1)
//For comma
&&
(charCode != 46 || $(element).val().indexOf('.') != -1) && (charCode < 48 || charCode > 57))
return false;
return true;
}
完成小提琴:https://jsfiddle.net/s2t8fgn3/
请您帮助我实现用户之后只能进入两个地方。或者,仅限于123.02,插入的逗号或圆点不应重复。
更新:我们还需要将粘贴复制到其中。那么如何管理数据是否是正确的小数以及如何允许CTRL + V而不是V。
答案 0 :(得分:3)
我会添加正则表达式检查
$(element).val().toString().match("\\.[0-9]{2,}$")
请参阅https://jsfiddle.net/2fpcg0ee/
更新:用于比较
之前和之后的值的不同方法$(document).ready(function() {
var oldVal = '';
$('.myTexbox').keypress(function (event) {
if (this.value.match("^[0-9]*[.,]?[0-9]{0,2}$"))
oldVal = this.value;
});
$('.myTexbox').keyup(function (event) {
if (!this.value.match("^[0-9]*[.,]?[0-9]{0,2}$")) {
$('.myTexbox').val(oldVal);
}
});
});
答案 1 :(得分:0)
我制作了一些代码,我希望这是你试图实现的目标
function validateDecimal(num) {
//goal: decimal number, only one [.,] allowed, only 2 digits after [.,]
//first we check for invalid numbers
var findInvalid = num.match(/[^0-9\,\.]/g);
if(findInvalid) //found invalid chars
return false;
//now replace , to . (dot is more machinelike)
var num = num.replace(/,/g,".");
//now find number of occurences of .
var count = (num.match(/\./g) || []).length;
if(count > 1)
return false; //we have more than one . -> so its invalid
//now we count the chars after the first .
var indexOfDot = num.indexOf(".");
if(indexOfDot == -1)
return true; //we have no dot - so its pure numeric (no decimal)
var charsAfterDot = num.length - (indexOfDot+1);
if(charsAfterDot > 2)
return false; //we have more than 2 chars after dot - invalid
return true; //every other case is valid
}
http://jsfiddle.net/7Ls7L3u9/&lt;&lt;&lt;摆弄