/**
* 检查是否为数字
*
* @param {}
* str
* @return {Boolean} true:数字,false:<b>不是</b>数字;
*/
var isNum = function(str) {
var re = /^(-?\d+)(\.\d+)?$/
return re.test(str);
}
/**
* input校验只能输入浮点数
*
* @param {}
* parent :父容器的
* selector :选择器
* @return {Boolean} true:数字,false:<b>不是</b>数字;
*/
var bindInputNumber = function(parent, selector) {
$(parent)
.delegate(
selector,
'keyup',
function() {
if ($(this).val() != "") {
if ($(this).val().indexOf(".") == $(this).val().length - 1) {
$(this).data("old", $(this).val());
} else if ($(this).val().lastIndexOf("-") == 0
&& $(this).val().length == 1) {
$(this).data("old", $(this).val());
} else if (!isNum($(this).val())) {
$(this).val($(this).data("old"));
} else {
$(this).data("old", $(this).val());
}
} else {
$(this).data("old", $(this).val());
}
});
$(parent)
.delegate(
selector,
'paste',
function() {
if ($(this).val() != "") {
if ($(this).val().indexOf(".") == $(this).val().length - 1) {
$(this).data("old", $(this).val());
} else if ($(this).val().lastIndexOf("-") == 0
&& $(this).val().length == 1) {
$(this).data("old", $(this).val());
} else if (!isNum($(this).val())) {
$(this).val($(this).data("old"));
} else {
$(this).data("old", $(this).val());
}
} else {
$(this).data("old", $(this).val());
}
});
$(parent)
.on(
"keyup",
selector,
function() {
if ($(this).val() != "") {
if ($(this).val().indexOf(".") == $(this).val().length - 1) {
$(this).data("old", $(this).val());
} else if ($(this).val().lastIndexOf("-") == 0
&& $(this).val().length == 1) {
$(this).data("old", $(this).val());
} else if (!isNum($(this).val())) {
$(this).val($(this).data("old"));
} else {
$(this).data("old", $(this).val());
}
} else {
$(this).data("old", $(this).val());
}
});
$(parent)
.on(
"paste",
selector,
function() {
if ($(this).val() != "") {
if ($(this).val().indexOf(".") == $(this).val().length - 1) {
$(this).data("old", $(this).val());
} else if ($(this).val().lastIndexOf("-") == 0
&& $(this).val().length == 1) {
$(this).data("old", $(this).val());
} else if (!isNum($(this).val())) {
$(this).val($(this).data("old"));
} else {
$(this).data("old", $(this).val());
}
} else {
$(this).data("old", $(this).val());
}
});
}
jquery 数据校验,input只能输入浮点数
最新推荐文章于 2023-04-19 10:50:00 发布