var JVerify = { role: { number: /[0-9/]/, decimal: /[0-9./]/, code: /[0-9A-Z]/ }, Verify: function () { for (var prop in JVerify.role) { $("[role^='" + prop + "']").each(function () { var obj = $(this); var values = obj.attr("role").split("-"); var length = 16; if (values.length > 1) { length = values[1]; } obj.attr("maxlength", length); obj.bind("input propertychange", function () { var input = $(this); var text = input.val(); input.val(""); var content = ""; var attr = $(this).attr("role"); var regex = JVerify.role[values[0]]; var isDot = false; var array = attr.split("-"); var number = length; if (array.length == 3) { number = Number(array[2]); } for (var i = 0, index = 0; i < text.length; i++) { if (text[0] == ".") { continue; } if (text[i] == ".") { if (isDot == false) { content += "."; isDot = true; index = i; } continue; } if ((i - 0 == 1 && text[0] == "0" && text[i] == "0") || isDot && (index + number < i)) { continue; } if (regex.test(text[i])) { content += text[i]; } } input.val(content); }).blur(function () { var value = $(this).val(); if (value[value.length - 1] === ".") { $(this).val(value.substr(0, value.length - 1)); } }); }) } } }
如只需输入小数,屏蔽非数字字符,在html中的input元素input添加属性role=“decimal-6-1”即可,尾数6为input的输入长度,1的意思为保留1位小数,调用代码如下:
<input role="decimal-6-1" type="text" />
JVerify.Verify();
如需自定义正则表达式,给JVerify.role添加属性即可,如下所示:
JVerify.role.myRegex = /[a-z]/;