JS常用表单验证方法总结


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>表单验证</title>
<script language="javascript">
function check_1(param){//不为空
if(param==""||param==null){return false;}else{return true;}
}
function check_2(param){//长度限制,字母是10个,汉字也是10个
if(param.length>10){return false;}else{return true;}
}
function check_3(param){//只能输入汉字
var pattern= /^[\u4e00-\u9faf]+$/;
var flag = pattern.test(param);
if(flag==false){return false;}else{return true;}
}
function check_4(param){//只能输入数字
var pattern= /^[0-9]+$/;
var flag = pattern.test(param);
if(flag==false){return false;}else{return true;}
}
function check_5(param){//只能输入数字字母下划线
var pattern= /^[0-9a-zA-z_]+$/;
var flag = pattern.test(param);
if(flag==false){return false;}else{return true;}
}
function check_6(param){//邮箱格式验证
var pattern= /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
var flag = pattern.test(param);
if(flag==false){return false;}else{return true;}
}
function check_7(param){//网址格式验证
var pattern= /^((https|http|ftp|rtsp|mms)?:\/\/)?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?(([0-9]{1,3}\.){3}[0-9]{1,3}|([0-9a-z_!~*'()-]+\.)*([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\.[a-z]{2,6})(:[0-9]{1,4})?((\/?)|(\/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+\/?)$/;
var flag = pattern.test(param);
if(flag==false){return false;}else{return true;}
}
function check(){
var value=document.getElementById("testValue").value;
var result=check_7(value);//在这里设置验证函数的名称,我写了check_1~check_7七个常用的表单验证函数
if(result==false){
document.getElementById("testValue").style.border="2px solid red";
}else{
//document.getElementById("testValue").style.border="2px solid green";
document.getElementById("testValue").style.border="";
}
}
</script>
</head>
<body>
<div>
请输入: <input type="text"></input>
<input type="button" value="点击验证"></input>
</div>
</body>
</html>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgpfjy.html