html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="inputVerification.js" type="text/javascript"></script>
</head>
<body>
<label style="display: inline-block;width: 100px">整数:</label><input type="text" regexInput="int"/><!-- 整数 -->
<br><label style="display: inline-block;width: 100px">小数整数:</label><input type="text" regexInput="number"/><!-- 小数整数 -->
<script type="text/javascript">
InputUtil.limitInputFormat();
</script>
</body>
</html>
js:
var InputUtil = {
/**
*数字,中文,字母,double 类型输入限制;
*只要在input标签上加上jInput="int,chinese,english,double"
*/
limitInputFormat: function() {
_limitInputFormat();
}
};
/**
* [_limitInputFormat description]
* @param {[type]} browserType [description]
* @return
*/
function _limitInputFormat() {
var inputType=['int','chinese','english','double','number'];
var inputs = document.getElementsByTagName("input");
for(var i=0;i<inputs.length;i++){
if(inputs[i].type=="text"){
inputs[i].addEventListener('input' ,function(e){
if (this.getAttribute("regexInput")!=null) {
var input_type = this.getAttribute('regexInput').split(',');
var value = this.value;
if (!input_type && input_type.length <= 0) {
return;
}
var values_of_type = [];
var RegStr = '^[';
for (var i = 0; i < input_type.length; i++) {
if (input_type[i]) {
if (input_type[i] == 'int') {
RegStr += '\\d';
} else if (input_type[i] == 'chinese') {
RegStr += '\\u4e00-\\u9fa5';
} else if (input_type[i] == 'number') {
RegStr += '\\d+$|^\\d*\\.?\\d+$';
} else if (input_type[i] == 'english') {
RegStr += 'a-zA-Z';
} else if (input_type[i] == 'double') {
RegStr = '^[\\+\\-]?\\d+\\.?\\d+';
this.value = value.match(new RegExp(RegStr, 'g'));
return;
}
}
}
RegStr += ']*';
if (RegStr.length <= 3) {
return;
}
var expression = new RegExp(RegStr, 'g');
var return_value = value.match(expression);
this.value = return_value;
}
});
}
}
}