JQ 数字验证

时间:2021-06-02 09:46:19
 $.fn.extend({
checknum: function (min, max, accurate) {
if ($(this).val() != "") {
$(this).val(parseFloat($(this).val()).toFixed(accurate))
}
else {
$(this).val(parseFloat('0').toFixed(accurate))
}
$(this).bind('keyup', function () {
event = window.event || event;
if (event.keyCode == 37 || event.keyCode == 39) {
return;
}
var thisinput = $(this);
var st = '';
for (var i = 0; i < accurate; i++) {
st += '\\d';
}
st = '^(\\-)*(\\d+)\\.(' + st + ').*$';
if (accurate == 0) {
reg1 = /[^-\d]/g
}
else {
reg1 = /[^-\d.]/g
}
var reg = new RegExp(st)
if (thisinput.val().indexOf('-') > 0)
{
thisinput.val(thisinput.val().replace("-", ""));
}
thisinput.val(thisinput.val().replace(reg1, "").
replace(".", "$#$").replace(/\./g, "").replace("$#$", ".")
.replace("-", "$#$").replace(/\-/g, "").replace("$#$", "-")
.replace(reg, '$1$2.$3'));
if (thisinput.val() > max) {
if (thisinput.val().indexOf('.') == -1) {
var val = '' + max;
thisinput.val(thisinput.val().substring(0, val.length - 1))
}
else {
thisinput.val(max.toFixed(accurate));
}
}
if (thisinput.val() < min) {
thisinput.val(min.toFixed(accurate));
}
});
$(this).blur(function () {
if ($(this).val() == "") {
var tempval = 0;
tempval = tempval.toFixed(accurate);
$(this).val(tempval);
}
else {
$(this).val(parseFloat($(this).val()).toFixed(accurate));
}
});
$(this).focus(function () {
var tempval = 0;
tempval = tempval.toFixed(accurate);
if ($(this).val() == tempval || $(this).val() == '' || $(this).val() == '0') {
$(this).val("");
}
});
}
});