Copy the code code as follows:
function validateNum(obj) {
//Positive integer (caching is used here)
var number = obj.data(validate).number;
//Decimal point (caching is used here)
var decimal = obj.data(validate).decimal;
//Dynamic basic verification regularity
eval("var reg = /^[0-9]{0," + number + "}([.]?[0-9]{0," + decimal + "})$" + "/g;" );
var value = obj.val();
var maxnumlen = number + decimal + 1; //Maximum length + 1 (decimal point)
if (!reg.test(obj.val())) return false;
//The maximum length is equal to the length of the current value and the value does not have "."
if (maxnumlen == value.length && value.indexOf('.') <= 0) {
return false;
}
//Try to get the index of "."
var valueindexof = value.indexOf('.');
if (valueindexof > 0) {
//If the bit after the "." index is empty, then it will definitely return false.
if (value.charAt(valueindexof + 1) == "") {
return false;
}
}
//Split the value to easily determine the content before and after
var valuesplit = value.split('.');
//If the length of the value is greater than the defined positive integer length
if (value.length > number) {
if (valuesplit. length == 1) {
return false;
}
//Maximum length - the defined length is longer than the maximum length, false.
if (maxnumlen - number >= maxnumlen) {
return false;
}
}
return true;
}
After caching a validate object for the element, just call it.
definition:
$("#example").data("validate", { number: 2, decimal: 2 });
Call:
validateNum($("#example));