JS验证

很久前写的了..贴来充个数... :D

JS文件..
/*
* @editor Fatzhan Liang 2008/10/06
* @version 1.0 copyleft
* function: A simple js validator
* but now this codes can only run in the IE5(or higher version),
* compatibility is not considered yet cause lack of knowledge
*/

// public variable
var alltovalidate = new Array();
// initial the form to be validated
function initialForm(formId){
var elements = document.getElementById(formId).elements;
var parent;
var theLabel;
for(var i = 0; i < elements.length; i++){
if (elements[i].patternType == undefined) {
continue;
} else {
alltovalidate.push(elements[i]);
parent = elements[i].parentNode;
theLabel = document.createElement("label");
theLabel.style.visibility = "visible";
theLabel.style.font = "13px Verdana";
parent.appendChild(theLabel);
if (elements[i].type=="checkbox") {
var checkBoxes = document.getElementsByName(elements[i].name);
for (var temp = 0; temp < checkBoxes.length; temp++) {
checkBoxes.item(temp).attachEvent("onfocus", function(){showTip(checkBoxes.item(checkBoxes.length - 1));});
checkBoxes.item(temp).attachEvent("onblur", function(){validateOne(checkBoxes.item(checkBoxes.length - 1));});
}
} else {
elements[i].attachEvent("onfocus", showTip);
elements[i].attachEvent("onblur", validateOne);
}
}
}
}
// show the tip when focus
function showTip(obj){
obj = (obj.name == undefined ? obj.srcElement : obj);
var parent = obj.parentNode;
var theLabel = parent.lastChild;
ValidateRules.chooseTip(obj);
theLabel.style.background = "url(validator_image.gif) no-repeat 1px -40px";
theLabel.innerHTML = "<font color='black'> " + (obj.tip==undefined?ValidateRules.tip:obj.tip) + "</font>";
}
// validate one element
function validateOne(obj){
var isOk = false;
obj = (obj.name == undefined ? obj.srcElement : obj);
var parent = obj.parentNode;
var theLabel = parent.lastChild;
if (obj.value == ""){
if(obj.require == "no"){
theLabel.style.background = "url(validator_image.gif) no-repeat 1px -8px";
theLabel.innerHTML = "<font color='blue'> Empty is OK!</font>";
isOk = true;
} else {
theLabel.style.background = "url(validator_image.gif) no-repeat 1px -104px";
theLabel.innerHTML = "<font color='pink'> " + ValidateRules.warning + "!</font>";
isOk = false;
}
} else if (ValidateRules.doValidate(obj)){
theLabel.style.background = "url(validator_image.gif) no-repeat 1px -8px";
theLabel.innerHTML = "<font color='blue'> OK!</font>";
isOk = true;
} else {
theLabel.style.background = "url(validator_image.gif) no-repeat 1px -72px";
theLabel.innerHTML = "<font color='red'> " + (obj.error==undefined?ValidateRules.error:obj.error) + "!</font>";
isOk = false;
}
return isOk;
}
// validate all elements in the form
function validateForm(formId){
var pass = true;
for(var i = 0; i < alltovalidate.length; i++){
if(!validateOne(alltovalidate[i])) pass = false;
}
if(pass) document.getElementById(formId).submit();
}
// rules and relative functions
ValidateRules = {
tip: "please input",
error: "incorrect format",
warning: "cannot be empty",
require: /.+/,
email: /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,
mobile: /^((\(\d{2,3}\))|(\d{3}\-))?(13|15)\d{9}$/,
phone: /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}\-)?[1-9]\d{6,7}(\-\d{1,4})?$/,
postalcode: /^[1-9]\d{5}$/,
number: /^\d+$/,
integernum: /^[\-\+]?\d+$/,
doublenum: /^[\-\+]?[\d]+(\.[\d]+)?$/,
name: /^[\w\u4e00-\u9fa5\-]{1,20}$/,
username: /^\w{5,20}$/,
english: /^[A-Za-z]+$/,
chinese: /^[\u0391-\uFFE5]+$/,
varchar: /^[\w\W]{0,255}$/,
qq: /^[1-9]\d{4,9}$/,
url: /^(http:\/\/)?[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,
unsafe: /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,
safestring: "this.isSafe(value)",
date: "this.isDate(value, getAttribute('format'))",
idcard: "this.isIdCard(value)",
filter: "this.doFilter(value, getAttribute('accept'))",
limit: "this.doLimit(value.length,getAttribute('min'), getAttribute('max'))",
limitbyte: "this.doLimit(this.doLimitByte(value), getAttribute('min'), getAttribute('max'))",
repeat: "value == document.getElementById(getAttribute('match')).value",
range: "getAttribute('min') < (value|0) && (value|0) < getAttribute('max')",
compare: "this.doCompare(value,getAttribute('var'),getAttribute('type'))",
group: "this.doChecked(getAttribute('name'), getAttribute('min'), getAttribute('max'))",
select: "value != -1",
//selectMuti: "",
custom: "this.verifyCustom(getAttribute('pattern'), value)",
isSafe: function(input){
return !this.unsafe.test(input);
},
isDate: function(input, format){
switch(format){
case "ymd":
return /^(18|19|20|21)\d{2}-(0?\d|1[012])-(0?\d|[12]\d|3[01])$/.test(input);
break;
case "dmy":
return /^(0?\d|[12]\d|3[01]),(0?\d|1[012]),(18|19|20|21)\d{2}$/.test(input);
break;
default:
break;
}
},
isIdCard: function(input){
return true;
},
doFilter: function(input, acceptIn){
return new RegExp("^.+\.(?=INS)(INS)$".replace(/INS/g, acceptIn.split(/\s*,\s*/).join("|")), "gi").test(input);
},
doLimit: function(size, min, max){
min = min || 0;
max = max || Number.MAX_VALUE;
return min <= size && size <= max;
},
doLimitByte: function(input){
return input.replace(/[^\x00-\xff]/g,"**").length;
},
doCompare: function(input, cmp, type){
switch(type){
case "lt": return (input < cmp);
case "le": return (input <= cmp);
case "eq": return (input == cmp);
case "gt": return (input > cmp);
case "ge": return (input >= cmp);
case "ne": return (input != cmp);
default: return true;
}
},
doChecked: function(name, min, max){
var checkBoxes = document.getElementsByName(name);
var isChecked = 0;
min = min || 1;
max = max || checkBoxes.length;
for(var i = 0; i < checkBoxes.length; i++) {
if(checkBoxes[i].checked)
isChecked++;
}
return isChecked >= min && isChecked <= max;
},
verifyCustom: function(input, pattern){
return new RegExp(pattern,"gi").test(input);
},
chooseTip: function(obj){
with(obj){
var patternType = getAttribute("patternType");
if(typeof(patternType) == "object" || typeof(this[patternType]) == "undefined") {
return;
}
switch(patternType){
case "email": this.tip = "email format like fat@hotmail.com"; break;
case "mobile": this.tip = "mobile like (xx-)xxxxxxxxxxx"; break;
case "phone": this.tip = "separate the tele area num by '-'"; break;
case "postalcode": this.tip ="input a postalcode"; break;
case "number": this.tip = "input a correct number"; break;
case "integernum": this.tip = "input a integer"; break;
case "doublenum": this.tip = "input a double"; break;
case "name": this.tip = "chinese,english,'-'or'_' less than 20"; break;
case "username": this.tip = "english or number between 5 and 20"; break;
case "chinese": this.tip = "input chinese"; break;
case "varchar": this.tip = "less than 255 words"; break;
case "qq": this.tip = "input a correct qq"; break;
case "url": this.tip = "input a correct url"; break;
case "date": getAttribute("format") == "ymd" ? this.tip = "date format 2000-01-01" : this.tip = "date format 01,01,2000"; break;
case "safestring": this.tip = "larger than 5 words, do not use letter or number only"; break;
case "idcard": this.tip = "input a correct idcard"; break;
case "filter": this.tip = "only accept " + getAttribute("accept") + " format"; break;
case "limit": this.tip = "lenght between " + getAttribute("min") + " and " + getAttribute("max"); break;
case "limitbyte": this.tip = "only accept " + getAttribute("min") + " and " + getAttribute("max") + "bytes"; break;
case "repeat": this.tip = "repeat the last input"; break;
case "range": this.tip = "less than " + getAttribute("max") + " and greater than " + getAttribute("min"); break;
case "compare": this.tip = getAttribute("type") + " value " + getAttribute("var"); break;
case "group": this.tip = "must check " + getAttribute("min") + " to " + getAttribute("max"); break;
case "select": this.tip = "must select a value"; break;
default : break;
}
}
},
doValidate: function(obj){
var success = false;
with(obj){
var patternType = getAttribute("patternType");
if(typeof(patternType) == "object" || typeof(this[patternType]) == "undefined") {
success = false;
}
switch(patternType){
case "safestring":
case "repeat":
case "date":
case "idcard":
case "filter":
case "limit":
case "limitbyte":
case "range":
case "compare":
case "group":
case "select":
case "custom":
if(eval(this[patternType])) {
success = true;
}
break;
default:
if(this[patternType].test(value)){
success = true;
}
break;
}
}
return success;
}
}
function addEvent(node, evType, fn) {
if(node.addEventListener){
node.addEventListener(evType, fn, false);
return true;
} else if (node.attachEvent) {
alert("node.attachevent");
var r = node.attachEvent("on" + evType, fn);
return r;
} else {
alert(node["on" + evType]);
node["on" + evType] = fn;
}
}

=====================================

Html文件测试:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled1</title>

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=GB18030">

<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript" src="MyValidator.js"></script>
</head>

<body οnlοad="initialForm('testform');">
This is my HTML page. <br>
<form id="testform" action="comeon.html">
<table style="font: 14px Verdana">
<tr>
<th>username:</th>
<td><input name="input1" type="text" patternType="username"></td>
</tr>
<tr>
<th>password:</th>
<td><input id="password" name="input1" type="password" patternType="safestring"></td>
</tr>
<tr>
<th>repeat psw:</th>
<td><input name="input1" type="password" patternType="repeat" match="password"></td>
</tr>
<tr>
<th>your name:</th>
<td><input name="input1" type="text" patternType="name"></td>
</tr>
<tr>
<th>sex:</th>
<td><select name="select" patternType="select">
<option value="-1">your sex:</option>
<option value="0">GG</option>
<option value="1">MM</option>
<option value="1">MG</option>
</select></td>
</tr>
<tr>
<th>age:</th>
<td><input type="text" patternType="range" min="18" max="100" tip="age should between 18 and 100" error="you are too old or too young"/></td>
</tr>
<tr>
<th>birthday:</th>
<td><input name="input1" type="text" patternType="date" format="ymd" error="custom error1"/></td>
</tr>
<tr>
<th>idcard:</th>
<td><input name="input1" type="text" patternType="idcard"/>(未实现)</td>
</tr>
<tr>
<th>qq:</th>
<td><input name="input1" type="text" patternType="qq"/></td>
</tr>
<tr>
<th>email:</th>
<td><input name="input2" type="text" patternType="email"></td>
</tr>
<tr>
<th>favorite:</th>
<td><input type="checkbox" name="shit"/>jump <input type="checkbox" name="shit"/>fly <input type="checkbox" name="shit" validate="true" patternType="group" min="0" max="2"/>sleep</td>
</tr>
<tr>
<th>your head:</th>
<td><input name="input5" type="file" patternType="filter" accept="jpg,jpeg,png,gif"/></td>
</tr>
<tr>
<th>telephone:</th>
<td><input name="input3" patternType="phone" require="no"></td>
</tr>
<tr>
<th>moblie:</th>
<td><input name="input3" patternType="mobile"></td>
</tr>
<tr>
<th>postalcode:</th>
<td><input patternType="postalcode"/></td>
</tr>
<tr>
<th>your website:</th>
<td><input name="input3" patternType="url"></td>
</tr>
<tr>
<th>self intro:</th>
<td><textarea name="input4" cols="30" rows="5" patternType="limit" min="20" max="255"></textarea></td>
</tr>
<tr>
<th>test userdefined:</th>
<td><input name="input3" patternType="custom" pattern="I am a pig" tip="please input 'I am a pig'" error="you're not a pig"></td>
</tr>
<tr>
<td colspan="2" align="left"><input type="button" value="submit" οnclick="validateForm('testform')"/>
<input type="reset" value="reset"/></td>
</tr>
</table>
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值