js验证表单大全
前端表单验证之------史上最全JS表单验证封装类
前端表单验证之------史上最全JS表单验证封装类/*****************************************************************表单校验⼯具类 (linjq)*****************************************************************/$("#usename").val()!=""; //验证⾮空/*** 判断整数num是否等于0** @param num* @return* @author jiqinlin*/function isIntEqZero(num){return num==0;}/*** 判断整数num是否⼤于0** @param num* @return* @author jiqinlin*/function isIntGtZero(num){return num>0;}/*** 判断整数num是否⼤于或等于0** @param num* @return* @author jiqinlin*/function isIntGteZero(num){return num>=0;}/*** 判断浮点数num是否等于0** @param num 浮点数* @return* @author jiqinlin*/function isFloatEqZero(num){return num==0;}/*** 判断浮点数num是否⼤于0** @param num 浮点数* @return* @author jiqinlin*/function isFloatGtZero(num){return num>0;}/*** 判断浮点数num是否⼤于或等于0** @param num 浮点数* @return* @author jiqinlin*/function isFloatGteZero(num){return num>=0;}/*** 匹配Email地址*/function isEmail(str){if(str==null||str=="") return false;var result=str.match(/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/);if(result==null)return false;return true;}/*** 判断数值类型,包括整数和浮点数*/function isNumber(str){if(isDouble(str) || isInteger(str)) return true;return false;}/*** 只能输⼊数字[0-9]*/function isDigits(str){if(str==null||str=="") return false;var result=str.match(/^\d+$/);if(result==null)return false;return true;}/*** 匹配money*/function isMoney(str){if(str==null||str=="") return false;var result=str.match(/^(([1-9]\d*)|(([0-9]{1}|[1-9]+)\.[0-9]{1,2}))$/);if(result==null)return false;return true;}/*** 匹配phone*/function isPhone(str){if(str==null||str=="") return false;var result=str.match(/^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/); if(result==null)return false;return true;}/*** 匹配mobile*/function isMobile(str){if(str==null||str=="") return false;var result=str.match(/^((\(\d{2,3}\))|(\d{3}\-))?((13\d{9})|(15\d{9})|(18\d{9}))$/);if(result==null)return false;return true;}/*** 联系电话(⼿机/电话皆可)验证*/function isTel(String text){if(isMobile(text)||isPhone(text)) return true;return false;}/*** 匹配qq*/function isQq(str){if(str==null||str=="") return false;var result=str.match(/^[1-9]\d{4,12}$/);if(result==null)return false;return true;}/*** 匹配english*/function isEnglish(str){if(str==null||str=="") return false;var result=str.match(/^[A-Za-z]+$/);if(result==null)return false;return true;}/*** 匹配integer*/function isInteger(str){if(str==null||str=="") return false;var result=str.match(/^[-\+]?\d+$/);if(result==null)return false;return true;}/*** 匹配double或float*/function isDouble(str){if(str==null||str=="") return false;var result=str.match(/^[-\+]?\d+(\.\d+)?$/);if(result==null)return false;return true;}/*** 匹配邮政编码*/function isZipCode(str){if(str==null||str=="") return false;var result=str.match(/^[0-9]{6}$/);if(result==null)return false;return true;}/*** 匹配URL*/function isUrl(str){if(str==null||str=="") return false;var result=str.match(/^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\’:+!]*([^<>\"])*$/); if(result==null)return false;return true;}/*** 匹配密码,以字母开头,长度在6-12之间,只能包含字符、数字和下划线。
经常用到的JS表单验证函数
经常⽤到的JS表单验证函数最近需要⽤到⽤户注册信息的表单验证,然后就查了好些资料,下⾯就给⼤家分享⼀下经常会⽤到的⼀些,JS表单验证函数,希望对⼤家有⽤。
//邮件校验1//邮件校验2//通过校验返回ture,否则返回false3function isEmail(emailStr) {4if (emailStr.length == 0) {5return fasle;6 } else {7var emailPat=/^(.+)@(.+)$/;8var specialChars="/(/)<>@,;:///"/./[/]";9var validChars="[^/s" + specialChars + "]";10var quotedUser="("[^"]*")";11 var ipDomainPat=/^(d{1,3})[.](d{1,3})[.](d{1,3})[.](d{1,3})$/;12 var atom=validChars + '+';13 var word="(" + atom + "|" + quotedUser + ")";14 var userPat=new RegExp("^" + word + "(/." + word + ")*$");15var domainPat=new RegExp("^" + atom + "(/." + atom + ")*$");16var matchArray=emailStr.match(emailPat);17if (matchArray == null) {18return false;19 }20var user=matchArray[1];21var domain=matchArray[2];22if (user.match(userPat) == null) {23return false;24 }25var IPArray = domain.match(ipDomainPat);26if (IPArray != null) {27for (var i = 1; i <= 4; i++) {28if (IPArray[i] > 255) {29return false;30 }31 }32return true;33 }34var domainArray=domain.match(domainPat);35if (domainArray == null) {36return false;37 }38var atomPat=new RegExp(atom,"g");39var domArr=domain.match(atomPat);40var len=domArr.length;41if ((domArr[domArr.length-1].length < 2) ||42 (domArr[domArr.length-1].length > 3)) {43return false;44 }45if (len < 2) {46return false;47 }48return true;49 }50 }51view code////IP地址校验//正确的IP地址回ture,否则返回falsefunction isIp(strIp) {var ipDomainPat=/^((2[0-4]d|25[0-5]|[01]?dd?).){3}(2[0-4]d|25[0-5]|[01]?dd?)$/;var matchArray=strIp.match(ipDomainPat);if(matchArray!=null){return true;}}//电话号码校验//正确的电话号码(包括区号和“-”如0571-*******[8] 010-*******[8] )则返回ture,否则返回falsefunction isTelphoneNum(telNum){var telphoneNumPat=/^0d{2}-d{7,8}|0d{3}-d{7,8}$/;var matchArray=telNum.match(telphoneNumPat);if(matchArray!=null){return true;}}//⼿机号码校验//正确的⼿机号码(如:138******** 013800571505)则返回ture,否则返回false function isMobilephoneNum(mobileNum){var mobilephoneNumPat=/^1d{10}|01d{10}$/;var matchArray=mobileNum.match(mobilephoneNumPat);if(matchArray!=null){return true;}}//纯数字验证输⼊,输⼊为纯数字则返回ture,否则返回falsefunction isDigital(str){var digitalPot=/^d*$/;var matchArray=str.match(digitalPot);if(matchArray!=null){return true;}}//18位⾝份证验证,输⼊正确的号码返回ture,否则返回falsefunction card(id){var Wi=new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);var ai="10X98765432";var sum=0var ssum=0;for(var i=0;i<17;i++){ssum=eval(Wi[i]*id.charAt(i));sum=ssum+sum;}var modNum=sum%11;if(ai.charAt(modNum)==id.charAt(17)){return true;}}View Code//纯英⽂验证输⼊,判断是否为英⽂,正确返回ture,否则返回falsefunction isEnglish(name) {if(name.length == 0)return false;for(i = 0; i < name.length; i++) {if(name.charCodeAt(i) > 128)return false;}return true;}View Code//纯中⽂验证输⼊,判断是否为中⽂,正确返回 ture,否则返回falsefunction isChinese(name){if(name.length == 0)return false;for(i = 0; i < name.length; i++) {if(name.charCodeAt(i) > 128)return true;}return false;}View Code//⾮法字符判断,str中有charset则返回turefunction contain(str,charset){var i;for(i=0;i<charset.length;i++){if(str.indexOf(charset.charAt(i))>=0){return true;}return false;}}View Code//选中⽂本框或⽂本域⽂本,在input位置加上 onClick/onFocus="textSelect();" 然后就可以使⽤以下代码function textSelect() {var obj = document.activeElement;if(obj.tagName == "TEXTAREA"){obj.select();}if(obj.tagName == "INPUT" ) {if(obj.type == "text")obj.select();}}View Code//只允许输⼊字母,数字,下划线function textOnly(){var i= window.event.keyCode ;//8=backspace//9=tab//37=left arrow//39=right arrow//46=delete//48~57=0~9//97~122=a~z//65~90=A~Z//95=_if (!((i<=57 && i>=48)||(i>=97 && i<=122)||(i>=65 && i<=90)||(i==95)||(i==8)||(i==9)||(i==37)||(i==39)||(i==46))){//window.event.keyCode=27;event.returnValue=false;return false;} else {//window.event.keyCode=keycode;return true;}}View Code//判断URL,正确的URL返回true,否则返回falsefunction isURL(URL){var urlPat=/^http://[A-Za-z0-9]+.[A-Za-z0-9]+[/=?%-&_~`@[]':+!]*([^<>""])*$/;var matchArray=URL.match(urlPat);if(matchArray!=null){return true;} else {return false;}}View Code//判断短⽇期(如2003-5-23)function isDate(date){var r = date.match(/^(d{1,4})(-|/)(d{1,2})(d{1,2})$/);if(r==null){return false;}if (r[1]<1 || r[3]<1 || r[3]-1>12 || r[4]<1 || r[4]>31) {return false}var d= new Date(r[1], r[3]-1, r[4]);if(d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]){return true;}}View Code//判断短时间(HH:MM:SS)function isTime(time){var a = time.match(/^(d{1,2})(:)?(d{1,2})(d{1,2})$/);if (a == null){return false;}if (a[1]>23 || a[1]<0 || a[3]>60 || a[3]<0 || a[4]>60 || a[4]<0){return false}return true;}View Code//在表单元素中除button外,按回车键模拟TAB功能function enterToTab(){if (window.event.keyCode == 13 && window.event.ctrlKey == false && window.event.altKey == false){ if (window.event.srcElement.type != "button")window.event.keyCode = 9;} else {return true;}}View Code//在填写表单时按回车键提交表单,name为sumbit控件名function enterTOSubmit(name) {if (window.event.keyCode == 13 && window.event.ctrlKey == false && window.event.altKey == false){ var objSubmit=document.getElementById(name);objSubmit.focus;} else {return true;}}View Code//判断是否为浮点数,正确返回truefunction isFloat(float,index){var floatPat=/^(d{1,})[.](d{1,})$/;var matchArray=float.match(floatPat);if(matchArray!=null) {if(matchArray[2].length==index){return true;}}}View Code//判断字符最⼤长度,如果strin的长度不⼤于maxLen返回turefunction maxLength(strin,maxLen) {var len=0;for(var i=0;i<strin.length;i++){if(strin.charCodeAt(i)>256){len += 2;} else {len++;}}if(len<=maxLen){return true;}}View Code//判断字符最⼩长度,如果的长度不⼩于minLen返回turefunction minLength(strin,minLen) {var len=0;for(var i=0;i<strin.length;i++){if(strin.charCodeAt(i)>256){len += 2;} else {len++;}}if(len>=maxLen){return true;}}View Code//由三个函数组成checkPassWord(),charMode(),bitTotal()//校验密码复杂度,密码由数字,⼤⼩写字母,特殊字符中的任意三种组合,通过则返回true function checkPassWord(passWord,maxLen){if (passWord.length<=maxLen)return false; //密码太短Modes=0;for (i=0;i<passWord.length;i++){//测试⼀个字符并判断⼀共有多少种模式.Modes|=charMode(passWord.charCodeAt(i));}return bitTotal(Modes);}//CharMode函数//判断某个字符是属于哪⼀种类型.function charMode(iN){if (iN>=48 && iN <=57) //数字return 1;if (iN>=65 && iN <=90) //⼤写字母return 2;if (iN>=97 && iN <=122) //⼩写return 4;elsereturn 8; //特殊字符}//bitTotal函数//计算出当前密码当中⼀共有多少种模式function bitTotal(num){modes=0;for (i=0;i<4;i++){if (num & 1) modes++;num>>>=1;}if(modes==3){return true}}View Code//判断是否为合法的⽤户名,合法返回true,否则返回flase//⽤户名由字母和数字、下划线组成,且只能以字母开头,且长度最⼩为6位function isAccount(str){if(/^[a-z]w{3,}$/i.test(str)){return true;} else {return false;]}View Code//取得字符串中中⽂字的个数function getChineseNum(obstring){var pattern = /^[⼀-龥]+$/i;var maxL,minL;maxL = obstring.length;obstring = obstring.replace(pattern,"");minL = obstring.length; return (maxL - minL) }View Code。
js验证表单大全
js验证表单大全1.0姓名验证(非数字)^([\u4E00-\u9FA5]+|[a-zA-Z]+)$(非数字)^[\u4e00-\u9fa5]{1,}$(中文)出生日期/^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[1 3456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[ 2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$/1.1 长度限制<script>function test(){if(document.a.b.value.length>50){alert("不能超过50个字符!");document.a.b.focus();return false;}}</script><form name=a onsubmit="return test()"><textarea name="b" cols="40" wrap="VIRTUAL" rows="6"></textarea><input type="submit" name="Submit" value="check"></form>1.2 只能是汉字<input onkeyup="value="/oblog/value.replace(^[\u4E00-\u9FA5]+\W$,'')">1.3只能是英文^[a-zA-Z]{1,}[0-9a-zA-Z]*$|^[a-zA-Z]{1,}\w*[0-9a-zA-Z]$<script language=javascript>function onlyEng(){if(!(event.keyCode>=65&&event.keyCode<=90))event.returnvalue=false;}</script><input onkeydown="onlyEng();">1.4 只能是数字<script language=javascript>function onlyNum(){if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode< =105)))//考虑小键盘上的数字键event.returnvalue=false;}</script><input onkeydown="onlyNum();">1.5 只能是英文字符和数字<input onkeyup="value="/oblog/value.replace(/[\W]/g,"'') "onbeforepaste="clipbo ardData.setData('text',clipboardData.getData('text').replace(/[^\d]/g,''))">1.6 验证邮箱格式^([a-zA-Z0-9])+[@]+([a-zA-Z0-9]{1,4})+\.+([a-zA-Z0-9]{1,4})$<SCRIPT LANGUAGE=javascript RUNAT=Server>function isEmail(strEmail) {if (strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\. [A-Za-z0-9]+$/) != -1)return true;elsealert("oh");}</SCRIPT><input type=text onblur=isEmail(this.value)>1.7 屏蔽关键字(这里屏蔽***和****)<script language="javascript1.2">function test() {if((a.b.value.indexOf ("***") == 0)||(a.b.value.indexOf ("****") == 0)){alert(":)");a.b.focus();return false;}}</script><form name=a onsubmit="return test()"><input type=text name=b><input type="submit" name="Submit" value="check"></form>1.8 两次输入密码是否相同<FORM METHOD=POST ACTION=""><input type="password" id="input1"><input type="password" id="input2"><input type="button" value="test" onclick="check()"></FORM><script>function check(){with(document.all){if(input1.value!=input2.value){alert("false")input1.value = "";input2.value = "";}else document.forms[0].submit();}}</script>1.9屏蔽右键很酷oncontextmenu="return false" ondragstart="return false" onselectstart="return f alse"加在body中2.1 表单项不能为空<script language="javascript"><!--function CheckForm(){if (.value.length == 0) {alert("请输入您姓名!");.focus();return false;}return true;}--></script>2.2 比较两个表单项的值是否相同<script language="javascript"><!--function CheckForm()if (document.form.PWD.value != document.form.PWD_Again.value) {alert("您两次输入的密码不一样!请重新输入.");document.ADDUser.PWD.focus();return false;}return true;}--></script>2.3 表单项只能为数字和"_",用于电话/银行帐号验证上,可扩展到域名注册等<script language="javascript"><!--function isNumber(String){var Letters = "1234567890-"; //可以自己增加可输入值var i;var c;if(String.charAt( 0 )=='-')return false;if( String.charAt( String.length - 1 ) == '-' )return false;for( i = 0; i < String.length; i ++ ){c = String.charAt( i );if (Letters.indexOf( c ) < 0)return false;}return true;}function CheckForm(){if(! isNumber(document.form.TEL.value)) {alert("您的电话号码不合法!");document.form.TEL.focus();return false;}return true;}--></script>2.4 表单项输入数值/长度限定<script language="javascript"><!--function CheckForm(){if (document.form.count.value > 100 || document.form.count.value < 1) {alert("输入数值不能小于零大于100!");document.form.count.focus();return false;}if (document.form.MESSAGE.value.length<10){alert("输入文字小于10!");document.form.MESSAGE.focus();return false;}return true;}//--></script>2.5 中文/英文/数字/邮件地址合法性判断<SCRIPT LANGUAGE="javascript"><!--function isEnglish(name) //英文值检测{if(name.length == 0)return false;for(i = 0; i < name.length; i++) {if(name.charCodeAt(i) > 128)return false;}return true;}function isChinese(name) //中文值检测{if(name.length == 0)return false;for(i = 0; i < name.length; i++) {if(name.charCodeAt(i) > 128)return true;}return false;}function isMail(name) // E-mail值检测{if(! isEnglish(name))return false;i = name.indexOf(" at ");j = name dot lastIndexOf(" at ");if(i == -1)return false;if(i != j)return false;if(i == name dot length)return false;return true;}function isNumber(name) //数值检测{if(name.length == 0)return false;for(i = 0; i < name.length; i++) {if(name.charAt(i) < "0" || name.charAt(i) > "9") return false;}return true;}function CheckForm(){if(! isMail(form.Email.value)) {alert("您的电子邮件不合法!");form.Email.focus();return false;}if(! isEnglish(.value)) {alert("英文名不合法!");.focus();return false;}if(! isChinese(name.value)) {alert("中文名不合法!");name.focus();return false;}if(! isNumber(form.PublicZipCode.value)) {alert("邮政编码不合法!");form.PublicZipCode.focus();return false;}return true;}//--></SCRIPT>2.6 限定表单项不能输入的字符<script language="javascript"><!--function contain(str,charset)// 字符串包含测试函数{var i;for(i=0;i<charset.length;i++)if(str.indexOf(charset.charAt(i))>=0)return true;return false;}function CheckForm(){if ((contain(.value, "%\(\)><")) || (contain(document.for m.MESSAGE.value, "%\(\)><"))){alert("输入了非法字符");.focus();return false;}return true;}//--></script>1. 检查一段字符串是否全由数字组成---------------------------------------<script language="Javascript"><!--function checkNum(str){return str.match(/\D/)==null} alert(checkNum("1232142141"))alert(checkNum("123214214a1"))// --></script>2. 怎么判断是否是字符---------------------------------------if (/[^\x00-\xff]/g.test(s)) alert("含有汉字");else alert("全是字符");3. 怎么判断是否含有汉字---------------------------------------if (escape(str).indexOf("%u")!=-1) alert("含有汉字"); else alert("全是字符");4. 邮箱格式验证---------------------------------------//函数名:chkemail//功能介绍:检查是否为Email Address//参数说明:要检查的字符串//返回值:0:不是 1:是function chkemail(a){ var i=a.length;var temp = a.indexOf('@');var tempd = a.indexOf('.');if (temp > 1) {if ((i-temp) > 3){if ((i-tempd)>0){return 1;}}}return 0;}5. 数字格式验证--------------------------------------- //函数名:fucCheckNUM//功能介绍:检查是否为数字//参数说明:要检查的数字//返回值:1为是数字,0为不是数字function fucCheckNUM(NUM){var i,j,strTemp;strTemp="0123456789";if ( NUM.length== 0)return 0for (i=0;i<NUM.length;i++){j=strTemp.indexOf(NUM.charAt(i));if (j==-1){//说明有字符不是数字return 0;}}//说明是数字return 1;}6. 电话号码格式验证--------------------------------------- //函数名:fucCheckTEL//功能介绍:检查是否为电话号码//参数说明:要检查的字符串//返回值:1为是合法,0为不合法function fucCheckTEL(TEL){var i,j,strTemp;strTemp="0123456789-()# ";for (i=0;i<TEL.length;i++){j=strTemp.indexOf(TEL.charAt(i));if (j==-1){//说明有字符不合法return 0;}}//说明合法return 1;}7. 判断输入是否为中文的函数--------------------------------------- function ischinese(s){var ret=true;for(var i=0;i<s.length;i++)ret=ret && (s.charCodeAt(i)>=10000); return ret;}8. 综合的判断用户输入的合法性的函数---------------------------------------<script language="javascript">//限制输入字符的位数开始//m是用户输入,n是要限制的位数function issmall(m,n){if ((m<n) && (m>0)){return(false);}else{return(true);}}9. 判断密码是否输入一致--------------------------------------- function issame(str1,str2){if (str1==str2){return(true);}else{return(false);}}10. 判断用户名是否为数字字母下滑线--------------------------------------- function notchinese(str){var reg=/[^A-Za-z0-9_]/gif (reg.test(str)){return (false);}else{return(true); }}11. form文本域的通用校验函数---------------------------------------作用:检测所有必须非空的input文本,比如姓名,账号,邮件地址等等。
JS校验大全
2.5 只有小时和分钟,形如(12:03)
3、表单类
3.1 所有的表单的值都不能为空
3.2 多行文本框的值不能为空。
3.3 多行文本框的值不能超过sMaxStrleng
3.4 多行文本框的值不能少于sMixStrleng
3.5 判断单选框是否选择。
temp += "";
temp += "?";
temp += "0";
temp += "1";
temp += "x";
temp += "";
temp += "";
temp += content;
temp += "
return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[3]&&d.getDate()==r[4]);
}
2.3 长时间,形如 (2003-12-05 13:04:06)
function strDateTime(str)
{
var reg = /^(\d{1,4})(-|\/)(\d{1,2})\2(\d{1,2}) (\d{1,2})\d{1,2})\d{1,2})$/;
}
6.2 手机号码的验证
6.3 身份证的验证
function isIdCardNo(num)
{
if (isNaN(num)) {alert("输入的不是数字!"); return false;}
验证表单JS
本JS为表单验证通用插件使用时只需引用该JS文件即可对指定表单进行非空,非数字验证使用时需要验证项必须设置ID 且ID名称必须以“_”开头如<input type="text" id="_student">如需要验证是否为数字则另外需要在ID名称后加人Num 如<input type="text" id="_studentNum">最后提示信息必须在需要验证项后设置好必须指定ID 且ID 名称需为验证项ID 去除“_”如<lable id="student">学生不能为空</lable>如验证非空并验证是否为数字则需要设置2个提示框且提示非空的名称为去除“_”和Num的验证项ID 提示只能为数字的提示项只需去除“_”即可如<lable id="student">学生不能为空</lable> <lable id="studentNum">学生不能为空</lable>如需验证2次密码是否相同则需在2次密码框后都带有Pass 如<input type="text" id="_onePass"><input type="text" id="_twoPass">其中应有一条提示信息以pass作为ID 如<lable id="pass">2次密码不相同请检查后重新输入</lable>*/var name = null;//定义全局变量用来储存需要验证项IDvar labId = null;//定义全局变量用来储存需要提示项IDfunction checking(obj){//表单提交触发的验证方法obj传入需要验证的表单值如不传入则验证全部页面如页面中有多个表单一定要注意var isOk = true;//标记返回值验证全部通过时返true允许提交表单$input(obj);//调用方法获取对应表单所有需要验证的对象并储存在全局变量name 中$labName();//调用方法获取验证表单所有提示标签并储存在全局变量labId中for(var i = 0; i < name.length; i++){ //循环验证所有name中储存的表单if(labId[i].substr(name[i].length-4,3)!="Num"||name[i].substr(name[i].length-3,3)!="Num"){ if($id(name[i]).value==""){//验证非空$lab(i);//验证不通过时调用方法显示提示信息并定位光标isOk = false;break;}}else{if(isNaN($id(name[i]).value)){//验证是否为数字$lab(i);//验证不通过时调用方法显示提示信息并定位光标isOk = false;break;}}}if(name[name.length-2].substr(name[name.length-2].length-4,4)=="Pass"&&isOk==true){ if($id(name[name.length-2]).value != $id(name[name.length-1]).value){$lab("pass");isOk = false;}}return isOk;}function $lab(lab){//显示,隐藏提示信息并定位光标lab传入需要显示的信息for(var i = 0;i < labId.length; i++){if($id(labId[i])!=null){$id(labId[i]).style.display="none";}}if(!isNaN(lab)){if($id(labId[lab])!=null){$id(labId[lab]).style.display="";$id(labId[lab]).style.color="red";$id(labId[lab]).style.fontSize="9pt";$id(name[lab]).focus();}}else if($id(lab)!=null){$id(lab).style.display="";$id(lab).style.color="red";$id(lab).style.fontSize="9pt";$id(name[name.length-1]).focus();}}window.onload=$start;//加载页面时调用方法隐藏所有提示信息function $start(){$input();$labName();$lab(labId.length);if($id("pass")!=null){//对密码验证的特殊处理$id("pass").style.display="none";}}function $input(obj){//获取表单所有需要验证的信息传入表单ID 如为传入则获取页面中所有元素name = new Array()var list = new Array();var listSel = new Array();var listArea = new Array();if(obj==null){list = document.getElementsByTagName("input");//获取页面中所有input元素listSel = document.getElementsByTagName("select");//获取页面中所有select元素listArea = document.getElementsByTagName("textarea");//获取页面中所有textarea元素}else{list = $id(obj).getElementsByTagName("input");//获取表单中所有input元素listSel = $id(obj).getElementsByTagName("select");//获取表单中所有select元素listArea = $id(obj).getElementsByTagName("textarea");//获取表单中所有textarea 元素}var listId = new Array();var listStr = new Array();var nameNum = new Array();var pass = new Array();for(var i = 0,j=0; i < list.length+listSel.length+listArea.length; i++){//把所有表单元素ID存入一个数组以备后面方便使用if(i < list.length){listId[j++] = list[i].id;}else if(i >= list.length && i < list.length + listSel.length){listId[j++] = listSel[i - list.length].id;}else{listId[j++] = listArea[i - list.length - listSel.length].id;}}for(var i = 0,j = 0,k = 0,p = 0; i < listId.length; i++){//对获取到的元素验证得到需要进行验证的元素IDif(listId[i]!=""){if(listId[i].substr(0,1)=="_"){listStr[j++] = listId[i];}if(listId[i].charAt(0)=="_"&&listId[i].substr(listId[i].length-3,3)=="Num"){//获取需要验证是否数字的元素IDnameNum[k++]=listId[i];}if(listId[i].charAt(0)=="_"&&listId[i].substr(listId[i].length-4,4)=="Pass"){//获取需要验证密码相同的元素IDpass[p++] = listId[i];}}}for(var i = 0; i < listStr.length+nameNum.length+pass.length; i++){//把获取到的需要验证的元素存入全局变量nameif(i < listStr.length){name[i] = listStr[i];}else if(i >= listStr.length && i < listStr.length+nameNum.length){name[i] = nameNum[i-listStr.length];}else{name[i] = pass[i - listStr.length - nameNum.length];}//alert(name[i]);}//return name;}function $labName(){//获取所有提示信息IDlabId = new Array()for(var i = 0; i < name.length; i++){//循环所有需要验证的元素IDif(name[i].substr(name[i].length-3,3)!="Num"){//得到需要验证数字的提示信息的第一个ID 即非空IDlabId[i]=name[i].substr(1,name[i].length-1)+"l";}else{var isOk = false;for(var j = 0; j < labId.length; j++){//得到需要验证数字的提示信息的第二个ID 即只能为数字IDif(labId[j]==name[i].substr(1,name[i].length-4)+"l"){isOk = true;break;}}if(isOk){labId[i]=name[i].substr(1,name[i].length-1)+"l";}else{labId[i]=name[i].substr(1,name[i].length-4)+"l";}}}var labpp = new Array();labpp = labId;}function $id(obj){//简化document.getElementById(obj);return document.getElementById(obj);}示例<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>无标题文档</title><link href="css/css.css" rel="stylesheet" type="text/css" /><script type="text/javascript" language="javascript" src="js/checking.js"></script><script type="text/javascript" language="javascript" src="js/WebCalendar.js"></script></head><body class="showBody"><table width="100%" height="100%" border="0"><tr><td align="center" valign="top"><form id="myForm" name="form1" onsubmit="return checking('myForm')" method="post" action="admin.html">//调用js内验证方法<table width="100%" border="0" cellpadding="3" cellspacing="1" class="showTable"><tr class="logTitleTr"><td height="28" colspan="2" align="center">提交机房日志</td></tr><tr class="logInfoTr"><td width="15%" align="right">日期</td><td align="left"><input class="pass" type="text" name="textfield" id="_logTime" /><label id="logTimel"> *日期不能为空</label></td></tr><tr class="logInfoTr"><td align="right">班级名称</td><td align="left"><select name="select" id="_clName"><option>请选择班级</option><option value="1">cr0903</option></select> <label id="clNamel"> *请选择班级</label></td></tr><tr class="logInfoTr"><td align="right">班主任</td><td align="left"><input class="pass" type="text" name="textfield2" id="classMast"/></td></tr><tr class="logInfoTr"><td align="right">上机时间</td><td align="left"><select name="select2" id="_lessionTime"><option>请选择上机时间</option><option value="1">9:00-11:00</option></select> <label id="lessionTimel"> *上机时间不能为空</label> </td></tr><tr class="logInfoTr"><td align="right">课程名称</td><td align="left"><input class="pass" type="text" name="textfield3" id="_lessionPass"/><label id="lessionPassl"> *课程名称不能为空</label></td></tr><tr class="logInfoTr"><td align="right">辅导老师</td><td align="left"><input class="pass" type="text" name="textfield4" id="_lessionTeaPass"/><label id="lessionTeaPassl"> *辅导老师不能为空</label><label id="pass">*2次密码不相同</label></td></tr><tr class="logInfoTr"><td align="right">实到人数</td><td align="left"><input class="pass" type="text" name="textfield5" id="_trueStuNum"/><label id="trueStul"> *实到人数不能为空</label><label id="trueStuNuml"> *实到人数只能为数字</label></td></tr><tr class="logInfoTr"><td align="right">请假人数</td><td align="left"><input class="pass" type="text" name="textfield6" value="0" id="_leaveStuNum"/><label id="leaveStuNuml"> *请假人数只能为数字</label><label id="leaveStul"></label></td></tr><tr class="logInfoTr"><td align="right">旷机人数</td><td align="left"><input class="pass" type="text" name="textfield7" value="0" id="_TruantStuNum"/><label id="TruantStuNuml"> *旷机人数只能为数字</label><label id="TruantStu"></label></td></tr><tr class="logInfoTr"><td align="right">旷机名单</td><td align="left"><textarea name="textarea" class="tear" cols="30" rows="3"></textarea></td></tr><tr class="logInfoTr"><td align="right">违纪人数</td><td align="left"><input class="pass" type="text" name="textfield8" value="0" id="_DisobeyStuNum"/><label id="DisobeyStuNuml"> *违纪人数只能为数字</label><label id="DisobeyStu"></label></td></tr><tr class="logInfoTr"><td align="right">违纪名单</td><td align="left"><textarea name="textarea2" class="tear" cols="30" rows="3"></textarea></td></tr><tr class="logInfoTr"><td align="right">违纪事由及处理</td><td align="left"><textarea name="textarea3" class="tear" cols="30" rows="3"></textarea></td></tr><tr class="logInfoTr"><td align="right">机房环境及卫生</td><td align="left"><input class="pass" type="text" name="textfield9" /></td></tr><tr class="logInfoTr"><td align="right">备注</td><td align="left"><textarea name="textarea4" class="tear" cols="30" rows="3"></textarea></td></tr><tr class="logInfoTr"><td align="right"> </td><td align="left"><input type="submit" class="tear" value="提交" /><input type="reset" class="tear" value="重来" /></td></tr></table></form></td> </tr> </table> </body> </html>。
JS表单验证-12个常用的JS表单验证
JS表单验证-12个常⽤的JS表单验证JS表单验证-12个常⽤的JS表单验证最近有个项⽬⽤到了表单验证,⼩编在项⽬完结后的这段时间把常⽤的JS表单验证demo整理了⼀下,和⼤家⼀起分享~~~ 1. 长度限制<p>1. 长度限制</p><form name=a onsubmit="return test()"><textarea name="b" cols="40" rows="6" placeholder="不能超过50个字符!"></textarea><br /><input type="submit" name="Submit" value="check"></form><script language="javascript">function test(){if(document.a.b.value.length>50){alert("不能超过50个字符!");document.a.b.focus();return false;}}</script>2. 只能是汉字<p>2. 只能是汉字 </p><input type="text" onblur="isChinese(this.value)" placeholder="请输⼊中⽂!" /><script language="javascript">function isChinese(obj){var reg=/^[\u0391-\uFFE5]+$/;if(obj!=""&&!reg.test(obj)){alert('必须输⼊中⽂!');return false;}}</script>以下demo中的HTML的结构与验证中⽂结构相似的,⼩编就只写js啦~~~3. 只能是英⽂字母<script type="text/javascript">//验证只能是字母function checkZm(zm){var zmReg=/^[a-zA-Z]*$/;if(zm!=""&&!zmReg.test(zm)){alert("只能是英⽂字母!");return false;}}</script>4. 只能是数字<script language=javascript>//验证只能为数字function checkNumber(obj){var reg = /^[0-9]+$/;if(obj!=""&&!reg.test(obj)){alert('只能输⼊数字!');return false;}}</script>5. 只能是英⽂字母和数字<script type="text/javascript">//验证只能是字母和数字function checkZmOrNum(zmnum){var zmnumReg=/^[0-9a-zA-Z]*$/;if(zmnum!=""&&!zmnumReg.test(zmnum)){alert("只能输⼊是字母或者数字,请重新输⼊");return false;}}</script>6. 检验时间⼤⼩(与当前时间⽐较)<script type="text/javascript">//检验时间⼤⼩(与当前时间⽐较)function checkDate(obj){var obj_value=obj.replace(/-/g,"/");//替换字符,变成标准格式(检验格式为:'2009-12-10')// var obj_value=obj.replace("-","/");//替换字符,变成标准格式(检验格式为:'2010-12-10 11:12') var date1=new Date(Date.parse(obj_value));var date2=new Date();//取今天的⽇期if(date1>date2){alert("不能⼤于当前时间!");return false;}}</script>7. 屏蔽关键字(这⾥屏蔽***和****)<script type="text/javascript">function test(obj) {if((obj.indexOf ("***") == 0)||(obj.indexOf ("****") == 0)){alert("屏蔽关键字(这⾥屏蔽***和****)!");return false;}}</script>8. 两次输⼊密码是否相同<script type="text/javascript">function check(){with(document.all){if(input1.value!=input2.value){alert("密码不⼀致")input1.value = "";input2.value = "";}else {alert("密码⼀致");document.forms[0].submit();}}}</script>9. 表单项不能为空<script language="javascript">function CheckForm(obj){if (obj.length == 0) {alert("姓名不能为空!");return false;}return true;alert("姓名不能为空!");}</script>10. 邮箱验证<script language="javascript">function test(obj){//对电⼦邮件的验证var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/; if(!myreg.test(obj)){alert('请输⼊有效的邮箱!');return false;}}</script>11. 验证⼿机号<script type="text/javascript">function validatemobile(mobile){if(mobile.length==0){alert('⼿机号码不能为空!');return false;}if(mobile.length!=11){alert('请输⼊有效的⼿机号码,需是11位!');return false;}var myreg = /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/;if(!myreg.test(mobile)){alert('请输⼊有效的⼿机号码!');return false;}}</script>12. 验证⾝份证号码(需是有效⾝份证)<script type="text/javascript">// 构造函数,变量为15位或者18位的⾝份证号码function clsIDCard(CardNo) {this.Valid=false;this.ID15='';this.ID18='';this.Local='';if(CardNo!=null)this.SetCardNo(CardNo);}// 设置⾝份证号码,15位或者18位clsIDCard.prototype.SetCardNo = function(CardNo) {this.ID15='';this.ID18='';this.Local='';CardNo=CardNo.replace(" ","");var strCardNo;if(CardNo.length==18) {pattern= /^\d{17}(\d|x|X)$/;if (pattern.exec(CardNo)==null)return;strCardNo=CardNo.toUpperCase();} else {pattern= /^\d{15}$/;if (pattern.exec(CardNo)==null)return;strCardNo=CardNo.substr(0,6)+'19'+CardNo.substr(6,9)strCardNo+=this.GetVCode(strCardNo);}this.Valid=this.CheckValid(strCardNo);}// 校验⾝份证有效性clsIDCard.prototype.IsValid = function() {return this.Valid;}// 返回⽣⽇字符串,格式如下,1981-10-10clsIDCard.prototype.GetBirthDate = function() {var BirthDate='';if(this.Valid)BirthDate=this.GetBirthYear()+'-'+this.GetBirthMonth()+'-'+this.GetBirthDay(); return BirthDate;}// 返回⽣⽇中的年,格式如下,1981clsIDCard.prototype.GetBirthYear = function() {var BirthYear='';if(this.Valid)BirthYear=this.ID18.substr(6,4);return BirthYear;}// 返回⽣⽇中的⽉,格式如下,10clsIDCard.prototype.GetBirthMonth = function() {var BirthMonth='';if(this.Valid)BirthMonth=this.ID18.substr(10,2);if(BirthMonth.charAt(0)=='0')BirthMonth=BirthMonth.charAt(1);return BirthMonth;}// 返回⽣⽇中的⽇,格式如下,10clsIDCard.prototype.GetBirthDay = function() {var BirthDay='';if(this.Valid)BirthDay=this.ID18.substr(12,2);return BirthDay;}// 返回性别,1:男,0:⼥clsIDCard.prototype.GetSex = function() {var Sex='';if(this.Valid)Sex=this.ID18.charAt(16)%2;return Sex;}// 返回15位⾝份证号码clsIDCard.prototype.Get15 = function() {var ID15='';if(this.Valid)ID15=this.ID15;return ID15;}// 返回18位⾝份证号码clsIDCard.prototype.Get18 = function() {var ID18='';if(this.Valid)ID18=this.ID18;return ID18;}// 返回所在省,例如:上海市、浙江省clsIDCard.prototype.GetLocal = function() {var Local='';if(this.Valid)Local=this.Local;return Local;}clsIDCard.prototype.GetVCode = function(CardNo17) {var Wi = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2,1);var Ai = new Array('1','0','X','9','8','7','6','5','4','3','2');var cardNoSum = 0;for (var i=0; i<CardNo17.length; i++)cardNoSum+=CardNo17.charAt(i)*Wi[i];var seq = cardNoSum%11;return Ai[seq];}clsIDCard.prototype.CheckValid = function(CardNo18) {if(this.GetVCode(CardNo18.substr(0,17))!=CardNo18.charAt(17))return false;if(!this.IsDate(CardNo18.substr(6,8)))return false;var aCity={11:"北京",12:"天津",13:"河北",14:"⼭西",15:"内蒙古",21:"辽宁",22:"吉林",23:"⿊龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"⼭东",41:"河南",42:"湖北 ",43:"湖南",44:"⼴东",45:"⼴西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"⽢肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"⾹港",82:"澳门",91:"国外"};if(aCity[parseInt(CardNo18.substr(0,2))]==null)return false;this.ID18=CardNo18;this.ID15=CardNo18.substr(0,6)+CardNo18.substr(8,9);this.Local=aCity[parseInt(CardNo18.substr(0,2))];return true;}clsIDCard.prototype.IsDate = function(strDate) {var r = strDate.match(/^(\d{1,4})(\d{1,2})(\d{1,2})$/);if(r==null)return false;var d= new Date(r[1], r[2]-1, r[3]);return (d.getFullYear()==r[1]&&(d.getMonth()+1)==r[2]&&d.getDate()==r[3]);}function valiIdCard(idCard){var checkFlag = new clsIDCard(idCard);if (!checkFlag.IsValid()) {alert("输⼊的⾝份证号⽆效,请输⼊真实的⾝份证号!");document.getElementByIdx("idCard").focus();return false;}else{alert("是有效⾝份证!");}}</script>。
表单验证—js循环所有表单验证
表单验证—js循环所有表单验证【封装为表单验证的专⽤js,所有表单页⾯都可以调⽤】1、表单<form id="regForm" method="post" action="index/register" onsubmit="checkForm(this)">....<td><label class="ui-green"><input type="submit" name="submit" value="提交注册"/></label></td>2、验证form表单function checkForm(frm){var els = frm.getElementsByTagName("input");for(var i=0; i<els.length; i++) {if(typeof(els[i].getAttribute("onblur")) == "function") {if(!CheckItem(els[i])) return false;}}return true;}3、验证该表单下的所有input框function CheckItem(obj){//将input提⽰框的内容赋空obj.parentNode.parentNode.className = "";var msgBox = obj.parentNode.getElementsByTagName("span")[0];switch() {case "regUserName"://这后⾯的业务可以单独提出来作为⼀个⽅法if(obj.value == "") {msgBox.innerHTML = "密码不能为空!";//添加className⽅便统⼀管理样式msgBox.className = "error";return false;}else{//⽤户名被占⽤$.ajax({"url":"index/hasname","data":"username="+obj.value,"type":"post","dataType":"json","success":function(data){if(data=="1"){msgBox.innerHTML = "⽤户名已存在!";msgBox.className = "error";return false;}else{//⽤户名可⽤msgBox.innerHTML = "⽤户名可⽤!";msgBox.className = "nameinfo";}}});}break;case "userName":if(obj.value == "") {msgBox.innerHTML = "密码不能为空!";msgBox.className = "error";return false;}break;case "passWord":if(obj.value == "") {msgBox.innerHTML = "密码不能为空!";msgBox.className = "error";return false;}break;case "rePassWord":if(obj.value == "") {msgBox.innerHTML = "密码不能为空!";msgBox.className = "error";return false;} else if(obj.value != document.getElementById("passWord").value) { msgBox.innerHTML = "两次密码不⼀致!";msgBox.className = "error";return false;}break;case "veryCode":if(obj.value == "") {msgBox.innerHTML = "验证码不能为空!";msgBox.className = "error";return false;}break;}return true;}。
js表单合法性校验
js表单合法性校验/*** 取得字符串的字节长度*/ 代码function strlen(str){var i;var len;len = 0;for (i=0;i<str.length;i++){if (str.charCodeAt(i)>255) len+=2; else len++; }return len;}/** 判断是否为数字,是则返回true,否则返回false */function f_check_number(obj){if (/^\d+$/.test(obj.value)){return true;}else{f_alert(obj,"请输入数字");return false;}}/** 判断是否为自然数,是则返回true,否则返回false */function f_check_naturalnumber(obj){var s = obj.value;if (/^[0-9]+$/.test( s ) && (s > 0)){return true;}else{f_alert(obj,"请输入自然数");return false;}}/** 判断是否为整数,是则返回true,否则返回false */function f_check_integer(obj){if (/^(\+|-)?\d+$/.test( obj.value )){return true;}else{f_alert(obj,"请输入整数");return false;}}/** 判断是否为实数,是则返回true,否则返回false*/function f_check_float(obj){if (/^(\+|-)?\d+($|\.\d+$)/.test( obj.value )){return true;}else{f_alert(obj,"请输入实数");return false;}}/** 校验数字的长度和精度*/function f_check_double(obj){var numReg;var value = obj.value;var strValueTemp, strInt, strDec;var dtype = obj.eos_datatype;var pos_dtype = dtype.substring(dtype.indexOf("(")+1,dtype.indexOf(")")).split(",");var len = pos_dtype[0], prec = pos_dtype[1];try{numReg =/[\-]/;strValueTemp = value.replace(numReg, "");numReg =/[\+]/;strValueTemp = strValueTemp.replace(numReg, "");//整数if(prec==0){numReg =/[\.]/;if(numReg.test(value) == true){f_alert(obj, "输入必须为整数类型");return false;}}if(strValueTemp.indexOf(".") < 0 ){if(strValueTemp.length >( len - prec)){f_alert(obj, "整数位不能超过"+ (len - prec) +"位");return false;}}else{strInt = strValueTemp.substr( 0, strValueTemp.indexOf(".") );if(strInt.length >( len - prec)){f_alert(obj, "整数位不能超过"+ (len - prec) +"位");return false;}strDec = strValueTemp.substr( (strValueTemp.indexOf(".")+1), strValueTemp.length );if(strDec.length > prec){f_alert(obj, "小数位不能超过"+ prec +"位");return false;}}return true;}catch(e){alert("in f_check_double = " + e);return false;}}/** 校验数字的最小最大值* 返回bool*/function f_check_interval(obj){var value = parseFloat(obj.value);var dtype = obj.eos_datatype;var pos_dtype = dtype.substring(dtype.indexOf("(")+1,dtype.indexOf(")")).split (",");var minLimit = pos_dtype[0];var maxLimit = pos_dtype[1];var minVal = parseFloat(pos_dtype[0]);var maxVal = parseFloat(pos_dtype[1]);if(isNaN(value)){f_alert(obj, "值必须为数字");return false;}if((isNaN(minVal) && (minLimit != "-")) || (isNaN(maxVal) && (maxLimit != "+"))){f_alert(obj, "边界值必须为数字或-、+");return false;}if(minLimit == "-" && !isNaN(maxVal)){if(value > maxVal){f_alert(obj, "值不能超过" + maxVal);return false;}}if(!isNaN(minVal) && maxLimit == "+"){if(value < minVal){f_alert(obj, "值不能小于" + minVal);return false;}}if(!isNaN(minVal) && !isNaN(maxVal)){if(minVal > maxVal){f_alert(obj, "起始值" + minVal + "不能大于终止值" + maxVal); }else{if(!(value <= maxVal && value >= minVal)){f_alert(obj, "值应该在" + minVal + "和" + maxVal + "之间"); return false;}}}return true;}/*用途:检查输入字符串是否只由汉字组成如果通过验证返回true,否则返回false*/function f_check_zh(obj){if (/^[\u4e00-\u9fa5]+$/.test(obj.value)) {return true;}f_alert(obj,"请输入汉字");return false;}/** 判断是否为小写英文字母,是则返回true,否则返回false */function f_check_lowercase(obj){if (/^[a-z]+$/.test( obj.value )){return true;}f_alert(obj,"请输入小写英文字母");return false;}/** 判断是否为大写英文字母,是则返回true,否则返回false */function f_check_uppercase(obj){if (/^[A-Z]+$/.test( obj.value )){return true;}f_alert(obj,"请输入大写英文字母");return false;}/** 判断是否为英文字母,是则返回true,否则返回false*/function f_check_letter(obj){if (/^[A-Za-z]+$/.test( obj.value )){return true;}f_alert(obj,"请输入英文字母");return false;}/*用途:检查输入字符串是否只由汉字、字母、数字组成输入:value:字符串返回:如果通过验证返回true,否则返回false*/function f_check_ZhOrNumOrLett(obj){ //判断是否是汉字、字母、数字组成var regu = "^[0-9a-zA-Z\u4e00-\u9fa5]+$";var re = new RegExp(regu);if (re.test( obj.value )) {return true;}f_alert(obj,"请输入汉字、字母或数字");return false;}/*用途:校验ip地址的格式输入:strIP:ip地址返回:如果通过验证返回true,否则返回false;*/function f_check_IP(obj){var re=/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/; //匹配IP地址的正则表达式if(re.test( obj.value )){if( RegExp.$1 <256 && RegExp.$2<256 && RegExp.$3<256 && RegExp.$4<256) returntrue;}f_alert(obj,"请输入合法的计算机IP地址");return false;}/*用途:检查输入对象的值是否符合端口号格式输入:str 输入的字符串返回:如果通过验证返回true,否则返回false*/function f_check_port(obj){if(!f_check_number(obj))return false;if(obj.value < 65536)return true;f_alert(obj,"请输入合法的计算机IP地址端口号");return false;}/*用途:检查输入对象的值是否符合网址格式输入:str 输入的字符串返回:如果通过验证返回true,否则返回false*/function f_check_URL(obj){var myReg = /^((http:[/][/])?\w+([.]\w+|[/]\w*)*)?$/;if(myReg.test( obj.value )) return true;f_alert(obj,"请输入合法的网页地址");return false;}/*用途:检查输入对象的值是否符合E-Mail格式输入:str 输入的字符串返回:如果通过验证返回true,否则返回false*/function f_check_email(obj){var myReg = /^([-_A-Za-z0-9\.]+)@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/;if(myReg.test( obj.value )) return true;f_alert(obj,"请输入合法的电子邮件地址");return false;}/*要求:一、移动电话号码为11或12位,如果为12位,那么第一位为0二、11位移动电话号码的第一位和第二位为"13"三、12位移动电话号码的第二位和第三位为"13"用途:检查输入手机号码是否正确输入:s:字符串返回:如果通过验证返回true,否则返回false*/function f_check_mobile(obj){var regu =/(^[1][3][0-9]{9}$)|(^0[1][3][0-9]{9}$)/;var re = new RegExp(regu);if (re.test( obj.value )) {return true;}f_alert(obj,"请输入正确的手机号码");return false;}/*要求:一、电话号码由数字、"("、")"和"-"构成二、电话号码为3到8位三、如果电话号码中包含有区号,那么区号为三位或四位四、区号用"("、")"或"-"和其他部分隔开用途:检查输入的电话号码格式是否正确输入:strPhone:字符串返回:如果通过验证返回true,否则返回false*/function f_check_phone(obj){var regu =/(^([0][1-9]{2,3}[-])?\d{3,8}(-\d{1,6})?$)|(^\([0][1-9]{2,3}\)\d{3,8}(\(\d{1,6}\))?$)|(^\d{3,8}$)/;var re = new RegExp(regu);if (re.test( obj.value )) {return true;}f_alert(obj,"请输入正确的电话号码"); return false;}/* 判断是否为邮政编码 */function f_check_zipcode(obj){if(!f_check_number(obj))return false;if(obj.value.length!=6){f_alert(obj,"邮政编码长度必须是6位"); return false;}return true;}/*用户ID,可以为数字、字母、下划线的组合,第一个字符不能为数字,且总长度不能超过20。
js常用正则表达式表单验证代码(最全面)
js 常用正则表达式表单验证代码方法一:var re=/正则表达式/;re.test($("txtid").val())方法二:$("txtid").val.match(/正则表达式/);附:验证数字的正则表达式集(转载)验证数字:^[0-9]*$验证n位的数字:^\d{n}$验证至少n位数字:^\d{n,}$验证m-n位的数字:^\d{m,n}$验证零和非零开头的数字:^(0|[1-9][0-9]*)$验证有两位小数的正实数:^[0-9]+(.[0-9]{2})?$验证有1-3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$验证非零的正整数:^\+?[1-9][0-9]*$验证非零的负整数:^\-[1-9][0-9]*$验证非负整数(正整数+ 0)^\d+$验证非正整数(负整数+ 0)^((-\d+)|(0+))$验证长度为3的字符:^.{3}$验证由26个英文字母组成的字符串:^[A-Za-z]+$验证由26个大写英文字母组成的字符串:^[A-Z]+$验证由26个小写英文字母组成的字符串:^[a-z]+$验证由数字和26个英文字母组成的字符串:^[A-Za-z0-9]+$验证由数字、26个英文字母或者下划线组成的字符串:^\w+$验证用户密码:^[a-zA-Z]\w{5,17}$ 正确格式为:以字母开头,长度在6-18之间,只能包含字符、数字和下划线。
验证是否含有^%&',;=?$\" 等字符:[^%&',;=?$\x22]+验证汉字:^[\u4e00-\u9fa5],{0,}$验证Email地址:^\w+[-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$验证InternetURL:^http://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$ ;^[a-zA-z]+://(w+(-w+)*)(.(w+(-w+)*))*(?S*)?$验证电话号码:^(\(\d{3,4}\)|\d{3,4}-)?\d{7,8}$:--正确格式为:XXXX-XXXXXXX,XXXX-XXXXXXXX,XXX-XXXXXXX,XXX-XXXXXXXX,XXXXXXX,XXXXXXXX。
js正则表达式验证表单【完整版】
js正则表达式验证表单【完整版】效果图:图(1)初始图图(2)填⼊信息校验代码如下:<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>完整验证表单</title><style type="text/css">*{margin: 0;padding: 0;list-style:none;}body{background:#ccc;}.demo{width:400px;padding:40px;background:#efefef;border:solid 1px #666;margin:100px auto 0;line-height:40px;}label{display:inline-block;width:20%;}input{width:60%;}</style></head><body><div class="demo"><ul><li><label for="iptqq">Q Q:</label><input type="text" id="iptqq"><span></span></li><li><label for="iptPhone">⼿机:</label><input type="text" id="iptPhone"><span></span></li><li><label for="iptEmil">邮箱:</label><input type="text" id="iptEmil"><span></span></li><li><label for="iptNum">座机:</label><input type="text" id="iptNum"><span></span></li><li><label for="iptName">姓名:</label><input type="text" id="iptName"><span></span></li></ul></div></body><script type="text/javascript">(function(window){function $(id){return document.getElementById(id);};// 获取对象var iptqq = $("iptqq"),iptPhone = $("iptPhone"),iptEmil = $("iptEmil"),iptNum = $("iptNum"),iptName = $("iptName");// 正则验证表达式// 验证座机var rxNum = /^0[0-9]{2,3}-[0-9]{7,8}$/;// 验证QQvar rxqq = /^[1-9][0-9]{4,10}$/;// 验证⼿机var rxPhone = /^(13[0-9]|15[012356789]|18[0-9]|17[678]|14[57])[0-9]{8}$/;// 验证邮箱var rxEmil = /^\w+@\w+\.\w+$/;// 验证姓名var rxName = /^[\u4E00-\u9FA5]{2,}$/// 验证座机cation(iptNum,rxNum);// 验证QQcation(iptqq,rxqq);// 验证⼿机号cation(iptPhone,rxPhone);// 验证邮箱cation(iptEmil,rxEmil);// 验证姓名cation(iptName,rxName);// 封装验证函数function cation(element,regExp){element.onblur = function(){var txt = this.value;if( regExp.test( txt ) ){this.nextElementSibling.innerHTML = "正确"this.nextElementSibling.style.color = "green";}else{this.nextElementSibling.innerHTML = "错误"this.nextElementSibling.style.color = "red";}}}})(window)</script></html>以上就是本⽂的全部内容,希望本⽂的内容对⼤家的学习或者⼯作能带来⼀定的帮助,同时也希望多多⽀持!。
js格式验证大全
js格式验证⼤全1.⾝份证号码验证:var Common = {//⾝份证号验证IsIdCardNo: function (IdCard) {var reg = /^\d{15}(\d{2}[0-9X])?$/i;if (!reg.test(IdCard)) {return false;}if (IdCard.length == 15) {var n = new Date();var y = n.getFullYear();if (parseInt("19" + IdCard.substr(6, 2)) < 1900 || parseInt("19" + IdCard.substr(6, 2)) > y) {return false;}var birth = "19" + IdCard.substr(6, 2) + "-" + IdCard.substr(8, 2) + "-" + IdCard.substr(10, 2);if (!Common.IsDate(birth)) {return false;}}if (IdCard.length == 18) {var n = new Date();var y = n.getFullYear();if (parseInt(IdCard.substr(6, 4)) < 1900 || parseInt(IdCard.substr(6, 4)) > y) {return false;}var birth = IdCard.substr(6, 4) + "-" + IdCard.substr(10, 2) + "-" + IdCard.substr(12, 2);if (!Common.IsDate(birth)) {return false;}iW = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1);iSum = 0;for (i = 0; i < 17; i++) {iC = IdCard.charAt(i);iVal = parseInt(iC);iSum += iVal * iW[i];}iJYM = iSum % 11;if (iJYM == 0) sJYM = "1";else if (iJYM == 1) sJYM = "0";else if (iJYM == 2) sJYM = "x";else if (iJYM == 3) sJYM = "9";else if (iJYM == 4) sJYM = "8";else if (iJYM == 5) sJYM = "7";else if (iJYM == 6) sJYM = "6";else if (iJYM == 7) sJYM = "5";else if (iJYM == 8) sJYM = "4";else if (iJYM == 9) sJYM = "3";else if (iJYM == 10) sJYM = "2";var cCheck = IdCard.charAt(17).toLowerCase();if (cCheck != sJYM) {return false;}}return true;},//⽇期验证IsDate: function (strDate) {var strSeparator = "-"; //⽇期分隔符var strDateArray;var intYear;var intMonth;var intDay;var boolLeapYear;strDateArray = strDate.split(strSeparator);if (strDateArray.length != 3) return false;intYear = parseInt(strDateArray[0], 10);intMonth = parseInt(strDateArray[1], 10);intDay = parseInt(strDateArray[2], 10);if (isNaN(intYear) || isNaN(intMonth) || isNaN(intDay)) return false;if (intMonth > 12 || intMonth < 1) return false;if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intDay > 31 || intDay < 1)) return false;if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intDay > 30 || intDay < 1)) return false;if (intMonth == 2) {if (intDay < 1) return false;boolLeapYear = false;if ((intYear % 100) == 0) {if ((intYear % 400) == 0) boolLeapYear = true;}else {if ((intYear % 4) == 0) boolLeapYear = true;}if (boolLeapYear) {if (intDay > 29) return false;}else {if (intDay > 28) return false;}}return true;}};2.QQ号码Common.Valid = {//验证qq号码QQNum: function (str) {var reg = /^\s*\d{4,12}\s*$/g;return reg.test(str);},//空或有效格式验证器EmptyOrValid: function (validFunc) {var func = validFunc;if ($.type(validFunc) == "string")func = this[$.trim(validFunc)];return function (str) {return $.trim(str) === "" || func(str);}}};3.⼿机号码、电话号码、传真验证:$(function () {String.prototype.isMobile = function () {return (/^(?:13\d|15[012356789]|18[0256789]|147)-?\d{5}(\d{3}|\*{3})$/.test($.trim(this)));}String.prototype.isTel = function () {//"兼容格式: 国家代码(2到3位)-区号(2到3位)-电话号码(7到8位)-分机号(1-4位)"return (/^(([0\+]\d{2,3}-)?(0\d{2,3}\-)?([2-9]\d{6,7})+(\-\d{1,4})?$/.test($.trim(this)));}String.prototype.isTelMobile = function () {//"兼容格式: 国家代码(2到3位)-区号(2到3位)-电话号码(7到8位)-分机号(1-4位)"return (/^(([0\+]\d{2,3}-)?(0\d{2,3}\-)?([2-9]\d{6,7})+(\-\d{1,4})?|(?:13\d|15[012356789]|18[0256789]|147)-?\d{5}(\d{3}|\*{3}))?$/.test($.trim(this))); }});使⽤⽰例如下:if ($.trim($("#Phone").val()) != "" || $.trim($("#Fax").val()) != "") {if (!$.trim($("#Phone").val()).isTel()) {Common.ShowInfo("请输⼊正确的电话号码!");return;}if (!$.trim($("#Fax").val()).isTel()) {Common.ShowInfo("请输⼊正确的传真号!");return;}}if ($.trim($("#MobilePhone").val()) != "") {if (!$.trim($("#MobilePhone").val()).isMobile()) {Common.ShowInfo("请输⼊正确的⼿机号码!");return;}}$(function () {});密码验证(不能包含空格)String.prototype.hasSpace = function () {return (/(^\s+)|(\s+$)|(^\S*\s*\S$)/.test($.trim(this)));};if($("#Password").val().hasSpace()){//判断 //}。
JS验证大全
}
//--------------------------------Email格式判断
function ismail(email)
{
return(new RegExp(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]
//--------------------------------判断用户名(判断字符由字母和数字,下划线,点号组成.且开头
的只能是下划线和字母)
function isAccount(str)
{
if(/^[a-z]\w{3,}$/i.test(str)) //用户名由字母和数字、下划线组成,且只能以字母开头,且长
*4、admin_Size=改变TextArea输入框高度
*
*其它验证正则表达式
*Email : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
*Phone : /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,7}(\-\d{1,4})?$/
/**
*方法名:onClickSelect
*描述:点中text框的时候,选中其中的文字
*输入:空
*输出:空
**/
function onClickSelect()
{
var obj = document.activeElement;
js验证表单 -很全
js验证表单js验证表单不错的JS验证用途:校验ip地址的格式输入:strIP:ip地址返回:如果通过验证返回true,否则返回false;*/function isIP(strIP) {if (isNull(strIP)) return false;var re=/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/g //匹配IP地址的正则表达式if(re.test(strIP)){if( RegExp.$1 <256 && RegExp.$2<256 && RegExp.$3<256 && RegExp.$4<256) return true; }return false;}/*用途:检查输入字符串是否为空或者全部都是空格输入:str返回:如果全是空返回true,否则返回false*/function isNull( str ){if ( str == "" ) return true;var regu = "^[ ]+$";var re = new RegExp(regu);return re.test(str);}/*用途:检查输入对象的值是否符合整数格式输入:str 输入的字符串返回:如果通过验证返回true,否则返回false */function isInteger( str ){var regu = /^[-]{0,1}[0-9]{1,}$/;return regu.test(str);}/*用途:检查输入手机号码是否正确输入:s:字符串返回:如果通过验证返回true,否则返回false*/function checkMobile( s ){var regu =/^[1][3][0-9]{9}$/;var re = new RegExp(regu);if (re.test(s)) {return true;}else{return false;}}/*用途:检查输入字符串是否符合正整数格式输入:s:字符串返回:如果通过验证返回true,否则返回false */function isNumber( s ){var regu = "^[0-9]+$";var re = new RegExp(regu);if (s.search(re) != -1) {return true;} else {return false;}}/*用途:检查输入字符串是否是带小数的数字格式,可以是负数输入:s:字符串返回:如果通过验证返回true,否则返回false*/function isDecimal( str ){if(isInteger(str)) return true;var re = /^[-]{0,1}(\d+)[\.]+(\d+)$/;if (re.test(str)) {if(RegExp.$1==0&&RegExp.$2==0) return false;return true;} else {return false;}}/*用途:检查输入对象的值是否符合端口号格式输入:str 输入的字符串返回:如果通过验证返回true,否则返回false*/function isPort( str ){return (isNumber(str) && str<65536);}/*用途:检查输入对象的值是否符合E-Mail格式输入:str 输入的字符串返回:如果通过验证返回true,否则返回false*/function isEmail( str ){var myReg = /^[-_A-Za-z0-9]+@([_A-Za-z0-9]+\.)+[A-Za-z0-9]{2,3}$/; if(myReg.test(str)) return true;return false;}/*用途:检查输入字符串是否符合金额格式格式定义为带小数的正数,小数点后最多三位输入:s:字符串返回:如果通过验证返回true,否则返回false*/function isMoney( s ){var regu = "^[0-9]+[\.][0-9]{0,3}$";var re = new RegExp(regu);if (re.test(s)) {return true;} else {return false;}}/*用途:检查输入字符串是否只由英文字母和数字和下划线组成输入:s:字符串返回:如果通过验证返回true,否则返回false*/function isNumberOr_Letter( s ){//判断是否是数字或字母var regu = "^[0-9a-zA-Z\_]+$";var re = new RegExp(regu);if (re.test(s)) {return true;}else{return false;}}/*用途:检查输入字符串是否只由英文字母和数字组成输入:s:字符串返回:如果通过验证返回true,否则返回false*/function isNumberOrLetter( s ){//判断是否是数字或字母var regu = "^[0-9a-zA-Z]+$";var re = new RegExp(regu);if (re.test(s)) {return true;}else{return false;}}/*用途:检查输入字符串是否只由汉字、字母、数字组成输入:value:字符串返回:如果通过验证返回true,否则返回false*/function isChinaOrNumbOrLett( s ){//判断是否是汉字、字母、数字组成var regu = "^[0-9a-zA-Z\u4e00-\u9fa5]+$";var re = new RegExp(regu);if (re.test(s)) {return true;}else{return false;}}/*用途:判断是否是日期输入:date:日期;fmt:日期格式返回:如果通过验证返回true,否则返回false*/function isDate( date, fmt ) {if (fmt==null) fmt="yyyyMMdd";var yIndex = fmt.indexOf("yyyy");if(yIndex==-1) return false;var year = date.substring(yIndex,yIndex+4);var mIndex = fmt.indexOf("MM");if(mIndex==-1) return false;var month = date.substring(mIndex,mIndex+2);var dIndex = fmt.indexOf("dd");if(dIndex==-1) return false;var day = date.substring(dIndex,dIndex+2);if(!isNumber(year)||year>"2100" || year< "1900") return false; if(!isNumber(month)||month>"12" || month< "01") return false; if(day>getMaxDay(year,month) || day< "01") return false; return true;}function getMaxDay(year,month) {if(month==4||month==6||month==9||month==11)return "30";if(month==2)if(year%4==0&&year%100!=0 || year%400==0)return "29";elsereturn "28";return "31";}/*用途:字符1是否以字符串2结束输入:str1:字符串;str2:被包含的字符串返回:如果通过验证返回true,否则返回false*/function isLastMatch(str1,str2){var index = stIndexOf(str2);if(str1.length==index+str2.length) return true; return false;}/*用途:字符1是否以字符串2开始输入:str1:字符串;str2:被包含的字符串返回:如果通过验证返回true,否则返回false*/function isFirstMatch(str1,str2){var index = str1.indexOf(str2);if(index==0) return true;return false;}/*用途:字符1是包含字符串2输入:str1:字符串;str2:被包含的字符串返回:如果通过验证返回true,否则返回false*/function isMatch(str1,str2){var index = str1.indexOf(str2);if(index==-1) return false;return true;}/*用途:检查输入的起止日期是否正确,规则为两个日期的格式正确,且结束如期>=起始日期输入:startDate:起始日期,字符串endDate:结束如期,字符串返回:如果通过验证返回true,否则返回false*/function checkTwoDate( startDate,endDate ) { if( !isDate(startDate) ) {alert("起始日期不正确!");return false;} else if( !isDate(endDate) ) {alert("终止日期不正确!");return false;} else if( startDate > endDate ) {alert("起始日期不能大于终止日期!");return false;}return true;}/*用途:检查输入的Email信箱格式是否正确输入:strEmail:字符串返回:如果通过验证返回true,否则返回false*/function checkEmail(strEmail) {//var emailReg = /^[_a-z0-9]+@([_a-z0-9]+\.)+[a-z0-9]{2,3}$/; var emailReg = /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/;if( emailReg.test(strEmail) ){return true;}else{alert("您输入的Email地址格式不正确!");return false;}}/*用途:检查输入的电话号码格式是否正确输入:strPhone:字符串返回:如果通过验证返回true,否则返回false*/function checkPhone( strPhone ) {var phoneRegWithArea = /^[0][1-9]{2,3}-[0-9]{5,10}$/;var phoneRegNoArea = /^[1-9]{1}[0-9]{5,8}$/;var prompt = "您输入的电话号码不正确!" if( strPhone.length > 9 ) {if( phoneRegWithArea.test(strPhone) ){ return true;}else{alert( prompt );return false;}}else{if( phoneRegNoArea.test( strPhone ) ){ return true;}else{alert( prompt );return false;}}}/*用途:检查复选框被选中的数目输入:checkboxID:字符串返回:返回该复选框中被选中的数目*/function checkSelect( checkboxID ) {var check = 0;var i=0;if( document.all(checkboxID).length > 0 ) {for( i=0; i<document.all(checkboxID).length; i++ ) { if( document.all(checkboxID).item( i ).checked ) { check += 1;}}}else{if( document.all(checkboxID).checked )check = 1;}return check;}function getTotalBytes(varField) {if(varField == null)return -1;var totalCount = 0;for (i = 0; i< varField.value.length; i++) {if (varField.value.charCodeAt(i) > 127)totalCount += 2;elsetotalCount++ ;}return totalCount;}function getFirstSelectedValue( checkboxID ){var value = null;var i=0;if( document.all(checkboxID).length > 0 ){for( i=0; i<document.all(checkboxID).length; i++ ){ if( document.all(checkboxID).item( i ).checked ){ value = document.all(checkboxID).item(i).value; break;}}} else {if( document.all(checkboxID).checked )value = document.all(checkboxID).value;}return value;}function getFirstSelectedIndex( checkboxID ){var value = -2;var i=0;if( document.all(checkboxID).length > 0 ){for( i=0; i<document.all(checkboxID).length; i++ ) { if( document.all(checkboxID).item( i ).checked ) { value = i;break;}}} else {if( document.all(checkboxID).checked )value = -1;}return value;}function selectAll( checkboxID,status ){if( document.all(checkboxID) == null)return;if( document.all(checkboxID).length > 0 ){for( i=0; i<document.all(checkboxID).length; i++ ){document.all(checkboxID).item( i ).checked = status;}} else {document.all(checkboxID).checked = status;}}function selectInverse( checkboxID ) {if( document.all(checkboxID) == null)return;if( document.all(checkboxID).length > 0 ) {for( i=0; i<document.all(checkboxID).length; i++ ) {document.all(checkboxID).item( i ).checked = !document.all(checkboxID).item( i ).checked;}} else {document.all(checkboxID).checked = !document.all(checkboxID).checked;}function checkDate( value ) {if(value=='') return true;if(value.length!=8 || !isNumber(value)) return false;var year = value.substring(0,4);if(year>"2100" || year< "1900")return false;var month = value.substring(4,6);if(month>"12" || month< "01") return false;var day = value.substring(6,8);if(day>getMaxDay(year,month) || day< "01") return false;return true;}/*用途:检查输入的起止日期是否正确,规则为两个日期的格式正确或都为空且结束日期>=起始日期输入:startDate:起始日期,字符串endDate:结束日期,字符串返回:如果通过验证返回true,否则返回false*/function checkPeriod( startDate,endDate ) { if( !checkDate(startDate) ) {alert("起始日期不正确!");return false;} else if( !checkDate(endDate) ) {alert("终止日期不正确!");return false;} else if( startDate > endDate ) {alert("起始日期不能大于终止日期!");return false;}return true;}/*用途:检查证券代码是否正确输入:secCode:证券代码返回:如果通过验证返回true,否则返回false*/function checkSecCode( secCode ) {if( secCode.length !=6 ){alert("证券代码长度应该为6位");return false;}if(!isNumber( secCode ) ){alert("证券代码只能包含数字");return false;}return true;}/**************************************************** function:cTrim(sInputString,iType)description:字符串去空格的函数parameters:iType:1=去掉字符串左边的空格2=去掉字符串左边的空格0=去掉字符串左边和右边的空格return value:去掉空格的字符串****************************************************/ function cTrim(sInputString,iType){var sTmpStr = ' ';var i = -1;if(iType == 0 || iType == 1){while(sTmpStr == ' '){++i;sTmpStr = sInputString.substr(i,1);}sInputString = sInputString.substring(i);}if(iType == 0 || iType == 2){sTmpStr = ' ';i = sInputString.length;while(sTmpStr == ' '){--i;sTmpStr = sInputString.substr(i,1);}sInputString = sInputString.substring(0,i+1); }return sInputString;}/*。
经典js密码 用户名表单验证
直接修改为.HTML格式即可使用,欢迎提出更好的方法。
<html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"/><script type="text/javascript">function a(obj){var zhi=document.getElementById('a');zhi.innerHTML='';if(obj.value.length=='0'){zhi.innerHTML='账号不能为空';return false;exit;}else{zhi.innerHTML='√';return true;}alert("aaa");}<!--验证密码-->function p(obj){var zhi=document.getElementById('p');if(obj.value.length=="0"){zhi.innerHTML='密码不能为空';return false;exit;}else{zhi.innerHTML='√';return true;}}<!--判断两次密码是否一致-->function www(obj,obj2){//alert('aa');var a=document.getElementById('www');a.innerHTML='';if(obj.value!=obj2.value){a.innerHTML='两次密码不一致';return false;exit;}else{a.innerHTML='√';return true;}}</script></head><body><form method="post" action="" name="myform">姓名:<input type="text" name="username" onblur="a(this)" /><span id="a" style="color:red;font-size:12px;"></span><br>密码:<input type="password" name="pword" onblur="p(this)"/><span id="p" style="color:red;font-size:12px;"></span></br>确认密码:<input type="password" name="qrpword" onblur="www(this,document.myform.pword)" /><span id="www" style="color:red;font-size:12px;"></span></br><input type="submit" value="提交"/><input name="" type="button" class="userpsubmit" value="" id="add" onclick="check_all(document.myform)"></form></body></html>。
JS校验表单必填项
JS校验表单必填项JS校验⼀个逻辑:通过js获取⽂本框的值,去判断,当值为空的时候将提⽰⽂案的div的class添加hide属性,false,否则移除hide属性,true,触发提交简单写个⽰例:HTML部分:<div class="form-group"><label for="" class="col-sm-2 control-label">⽤户名</label><div class="col-sm-10"><input type="text" class="form-control" name="username" value="{{$hrInfo->username or old('username')}}" placeholder="请输⼊⽤户名"><div class="error-message hide"><span class="text-denger" style="color: red">必填</span></div></div></div>JS部分:<script>$(function () {$(":submit").click(function (e) {e.preventDefault();if (boolInfo()) {$('.add-hr-info').submit();}})function boolInfo() {var bool = false;// ⽤户名if ($('[name=username]').val()) {bool = true;$('[name=username]').next().addClass('hide');} else {bool = false;$('[name=username]').next().removeClass('hide');}return bool;}})</script>。
JavaScript验证表单函数大全.docx
JavaScript验证表单函数大全JavaScript验证表单函数大全3用途:校验ip地址的格式4输入:strIP: ip地址5返回:如果通过验证返回true,否则返回false;67*/8function isIP(strIP) {9if (isNull (strIP)) return false;lOvar re二厂(\d+)\・ (\d+)\・(\d+)\・ (\d+)$/g //匹配IP 地址的正则表达式llif(re. test(strIP))12{13if ( RegExp. $1 <256 & RegExp. $2<256 && RegExp. $3<256 && RegExp. $4〈256) return true;14}15return false;16}1718/**//*19用途:检查输入字符申是否为空或者全部都是空格20输入:str21返回:22如果全是空返回true,否则返回false23*/24function isNull( str ) {25if ( str == ) return true;26var regu = ]+$〃;27var re = new RegExp (regu):28return re. test(str);29}303132/**//*33用途:检查输入对象的值是否符合整数格式34输入:str输入的字符串35返回:如果通过验证返回true,否则返刨false 3637*/38function islnteger( str ) {39var regu =厂[-]{0,1}[0-9]{1, }$/;40return regu. test(str);41}4243/**//*44用途:检查输入手机号码是否正确45输入:46s:字符串47返回:48如果通过验证返回true,否则返回false4950*/51function checkMobile( s ) {52var regu 二厂[1] [3] [0-9] {9} $/;53var re 二new RegExp(regu):54if (re. test(s)) {55return true;56}else{57return false;58}59}606162/**//*63用途:检查输入字符串是否符合正整数格式64输入:65s:字符串66返凹:67如果通过验证返回true,否则返回false6869*/70function isNumber( s ) {7Ivar regu = 〃八[0-9]+$〃;72var re 二new RegExp(regu);73if (s.search(re) !二-1) {74return true;75} else {76return false;77}78}7980/**//*81用途:检查输入字符串是否是带小数的数字格式,可以是负数82输入:83s:字符串84返回:85如果通过验证返回true,否则返回false8687*/88function isDecimal( str ) {89if (islnteger(str)) return true;90var re =厂[-]{0, 1} (\d+) [\・] + (\d+) $/; 91if (re.test(str)) {92if (RegExp. $l==0&RegExp. $2==0) return false; 93return true;94} else {95return false;96}97}9899/**//*100用途:检查输入对象的值是否符合端口号格式101输入:str输入的字符串102返回:如果通过验证返回true,否则返刨false 103104*/105function isPort( str ){106return (isNumber(str) & str<65536);107}108109/**//*110用途:检查输入对象的值是否符合E-Ma订格式111输入:str输入的字符串112返回:如果通过验证返回true,否则返回false113114*/115function isEmail( str ) {116va.r myReg 二「[-_A-Za-zO-9]+@([_A-Za-zO-9]+\.) + [A-Za-zO-9]{2, 3}$/; 117if(myReg.test(str)) return true;118return false;119}120121/**//*122用途:检查输入字符串是否符合金额格式123格式定义为带小数的正数,小数点后最多三位124输入:125s:字符串126返回:127如果通过验证返回true,否则返刨false128129*/130function isMoney( s ){13Ivar regu = 〃八[0-9] + [\・][0-9] {0, 3} $";132var re 二new RegExp(regu);133if (re. test(s)) {134return true;135} else {136return false;137}138}139/**//*140用途:检查输入字符串是否只由英文字母和数字和下划线组成141输入:142s:字符串143返回:144如果通过验证返回true,否则返刨false145146*/147function isNumberOr_Letter( s ) {//判断是否是数字或字母148149va.r regu = [0-9a-zA-Z\」+$〃;150var re 二new RegExp(regu);151if (re. test (s)) {152return true;153}else{154return false;155}156}157/**//*158用途:检查输入字符串是否只由英文字母和数字组成159输入:160s:字符串161返回:162如果通过验证返冋true,否则返冋false163164*/165function isNumberOrLetter( s ) {//判断是否是数字或字母166167var regu = 〃八[0-9a-zA-Z]+$〃;168va.r re 二new RegExp (regu);169if (re.test (s)) {170return true;171}else{172return false;173}174}175/**//*176用途:检查输入字符串是否只由汉字、字母、数字组成177输入:178value:字符串179返回:180如果通过验证返回true,否则返回false181182*/183function isChinaOrNumbOrLett ( s ) {//判断是否是汉字、字母、数字组成184185var regu = E0-9a-zA-Z\u4e00-\u9fa5]+$z,;186va.r re = new RegExp (regu);187if (re.test(s)) {188return true;189}else{190return false;191}192}193194/**//*195用途:判断是否是FI期196输入:date: Fl期;fmt: H期格式197返回:如果通过验证返回true,否则返刨false198*/199function isDate( date, fmt ) {200if (fmt二二null) fmt二〃yyyyMMdd";20Ivar ylndex 二fmt. indexOf(〃yyyy〃);202if(ylndex二二-1) return false;203var year 二date・substring(ylndex, yIndex+4);204va.r mlndex = fmt. indexOf (〃MM〃);205if(mlndex二二-1) return false;206var month 二date・ substring (mlndex, inIndex+2);207va.r dlndex = fmt. indexOf (〃dd〃);208if(dlndex二二T) return false;209var day 二date・ substring(dlndex, dIndex+2);210if (! isNumber (year) | year>,,2100/, year< "1900") return false; 211if (! isNumber (month) | | month>/,12/,month< 〃01〃)return false; 212if (da.y>getMaxDay (year, month) | day< 〃01〃)return false;213return true;214}215216function getMaxDay(year, month) {217if(month二二4 〔month二二6 |month二二9| month二二11) 218return 〃30";219if(month==2)220if (year%4=0&year%100! =0 | | year%400=0) 221return "29〃;222else223return 〃28〃;224return 〃31〃;225}226227/**//*228用途:字符1是否以字符串2结束229输入:strl:字符串;str2:被包含的字符串230返回:如果通过验证返回true,否则返回false231232*/233function isLastMatch(strl, str2)234 {235var index 二str1.1astlndexOf(str2);236if (str1. length二二index+str2. length) return true; 237return false;238}239240241/**//*242用途:字符1是否以字符串2开始243输入:strl:字符串;str2:被包含的字符串244返回:如果通过验证返回true,否则返回false245246*/247function isFirstMatch(strl, str2)248 {249va.r index 二strl. indexOf (str2);250if (index二二0) return true;251return false:252}253254/**//*255用途:字符1是包含字符串2256输入:strl:字符串;str2:被包含的字符串257返回:如果通过验证返回true,否则返刨false258259*/260function isMatch(strl, str2)261 {262va.r index 二str 1. indexOf (str2);263if(index=-l) return false;264return true;265}266267268/**//*269用途:检查输入的起止H期是否正确,规则为两个Fl期的格式正确,270且结束如期〉二起始FI期271输入:272startDate:起始日期,字符串273endDate:结束如期,字符串274返回:275如果通过验证返回true,否则返刨false276277*/278function checkTwoDate( startDate, endDate ) {279if( !isDate(startDate) ) {280alert (〃起始R期不正确!〃);281return false:282} else if ( !isDate(endDate) ) {283alert (〃终止R期不正确!〃);284return false:285} else if( startDate > endDate ) {286alert (〃起始R期不能大于终止Fl期!〃);287return false;288}289return true;290}291292/**//*293用途:检查输入的Email信箱格式是否止确294输入:295strEma.il:字符串296返回:297如果通过验证返回true,否则返回false298299*/300function checkEmail(strEmail) {301//var emailReg 二厂[_a-zO-9]+@([_a-z0-9]+\・)+ [a~zO-9] {2, 3} $/;302var emailReg =厂[\w-] + (\. [\w-]+)*@[\w-] + (\・[\w-]+)+$/; 303if ( emailReg・test(strEma订)){304return true;305}else{306alert(z,您输入的Email地址格式不正确!〃);307return false;308}309}310311/**//*312用途:检查输入的电话号码格式是否正确313输入:314strPhone:字符串315返回:316如果通过验证返回true,否则返回false317318*/319function checkPhone ( strPhone ) {320var phoneRegWithArea = r [0] [1-9] {2,3}-[0-9]{5, 10}$/; 32Ivar phoneRegNoArea =厂[1-9] {1}[0-9] {5,8}$/;322var prompt二〃您输入的电话号码不正确!〃323if ( strPhone. length > 9 ) {324if ( phoneRegWithArea. test(strPhone) ) {325return true;326}else{327alert( prompt );328return false;329}330}else{331if ( phoneRegNoArea・test( strPhone ) ){332return true;333}else{334alert( prompt );335return false;336}337}338}function trim(str){str二str.replace(/( \s*)| (\s*$)/g, “〃); return str; }//获取smarty中exemodel的值转化为二进制,并判断星期儿2010/5/25 function toBin(intNum){var answer 二“〃;if (/\d+/・ test(intNum)){while(intNum !二0){answer 二Math.abs(intNum % 2) + answer; intNum 二parselnt(intNum / 2);}if (answer, length 二二0){〃c〃answer 二0 ;return answer:else{return 〃0〃;。
JavaScript正则表单验证(用户名、密码、确认密码、手机号、座机号、身份证号)
JavaScript正则表单验证(⽤户名、密码、确认密码、⼿机号、座机号、⾝份证号)1、关于JavaScript表单验证,如果使⽤双向绑定的前端js框架,会更容易的多。
但是博主还是建议⼤家不要脱离源⽣js本⾝。
因为源⽣js才是王道。
注意: a、代码中的错误提⽰可能会没有,在代码中找到 “错误.jpg” 图⽚,⾃⼰制作⼀个 b、验证的判断已经完成,只需要根据⾃⼰的验证规则进⾏表单验证,更换⾃⼰的正则表达式。
c、博主将错误提⽰图⽚插⼊本⽂档中。
需要更名为 “错误.jpg”,放到与html根⽬录下⽅可使⽤。
(错误提⽰图⽚)<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>Document</title></head><body><table border="1"><form action="正则验证⼿机号.html" name="form1" method="post" onsubmit="return test()"><tr><td align="right">⽤户名:</td><td><input type="text" name="username"></td><td><span id="namemsg">*</span></td></tr><tr><td align="right">密码:</td><td><input type="password" name="pwd"></td><td><span id="pwdmsg">*</span></td></tr><tr><td align="right">确认密码:</td><td><input type="password" name="pwd1"></td><td><span id="pwd1msg">*</span></td></tr><tr><td align="right">⼿机号:</td><td><input type="text" name="phone"></td><td><span id="iphone1">*</span></td></tr><tr><td align="right">座机号:</td><td><input type="text" name="phone1"></td><td><span id="iphone2">*</span></td></tr><tr><td align="right">⾝份证号:</td><td><input type="text" name="sfzid"></td><td><span id="sfzmsg">*</span></td></tr><tr><td colspan="3"><input type="submit" name="sub" value="注册"><input type="reset" name="ret" value="重置" onclick="test1()"></td></tr></form></table><script type="text/javascript">//⽤户名验证ername.onkeyup=function(){var reg=/^[a-zA-Z]{1}[A-Z|a-z|0-9]{5,29}/;if(reg.test(this.value)&&this.value.length>=6&&this.value.length<=30){document.getElementById("namemsg").innerHTML="输⼊正确";}else{document.getElementById("namemsg").innerHTML="<img src='错误.jpg' width='15' height='15'>";}}//密码验证document.form1.pwd.onkeyup=function(){var reg1=/[A-Za-z]+[0-9]+/;if(reg1.test(this.value)&&this.value.length>=6&&this.value.length<=8){document.getElementById("pwdmsg").innerHTML="输⼊正确";}else{document.getElementById("pwdmsg").innerHTML="<img src='错误.jpg' width='15' height='15'>"; }}//确认密码document.form1.pwd1.onkeyup=function(){if(this.value==document.form1.pwd.value&&this.value!=""){document.getElementById("pwd1msg").innerHTML="输⼊正确";}else{document.getElementById("pwd1msg").innerHTML="<img src='错误.jpg' width='15' height='15'>"; }}//⼿机号验证document.form1.phone.onkeyup=function(){var reg2=/^(13|14|15|17|18)[0-9]{9}/;if(reg2.test(this.value)&&this.value.length==11){document.getElementById("iphone1").innerHTML="输⼊正确";}else{document.getElementById("iphone1").innerHTML="<img src='错误.jpg' width='15' height='15'>"; }}//座机号验证document.form1.phone1.onkeyup=function(){var reg3=/^[0-9]{3,4}(\-{1})[0-9]{7,8}/;if(reg3.test(this.value)&&this.value.length==13||this.value.length==12){document.getElementById("iphone2").innerHTML="输⼊正确";}else{document.getElementById("iphone2").innerHTML="<img src='错误.jpg' width='15' height='15'>"; }}//⾝份证号验证document.form1.sfzid.onkeyup=function(){var reg4=/^\d{17}[(0-9)|X|x ]{1}/;if(reg4.test(this.value)&&this.value.length==18){document.getElementById("sfzmsg").innerHTML="输⼊正确";}else{document.getElementById("sfzmsg").innerHTML="<img src='错误.jpg' width='15' height='15'>"; }}//注册按钮⽅法function test(){var str="输⼊正确"if(document.getElementById("namemsg").innerHTML!==str){document.getElementById("namemsg").innerHTML="<img src='错误.jpg' width='15' height='15'>"; ername.focus();ername.value="";return false;}if(document.getElementById("pwdmsg").innerHTML!==str){document.getElementById("pwdmsg").innerHTML="<img src='错误.jpg' width='15' height='15'>"; document.form1.pwd.focus();document.form1.pwd.value="";return false;}if(document.getElementById("pwd1msg").innerHTML!==str){document.getElementById("pwd1msg").innerHTML="<img src='错误.jpg' width='15' height='15'>"; document.form1.pwd1.focus();document.form1.pwd1.value="";return false;}if(document.getElementById("iphone1").innerHTML!==str){document.getElementById("iphone1").innerHTML="<img src='错误.jpg' width='15' height='15'>"; document.form1.phone.focus();document.form1.phone.value="";return false;}if(document.getElementById("iphone2").innerHTML!==str){document.getElementById("iphone2").innerHTML="<img src='错误.jpg' width='15' height='15'>"; document.form1.phone1.focus();document.form1.phone.value="";return false;}}</script></body></html>。
JS表单验证
{
if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode<=105)))
//考虑小键盘上的数字键
event.returnvalue=false;
}
</script>
{
alert("false")
input1.value = "";
input2.value = "";
}
else document.forms[0].submit();
}
}
</script>
路政管理系统应用:
//非空验证
function checkoname(){
var casename= document.all['caseInfo.casename'].value;
</form>
2. 只能是汉字
<input onkeyup="value="/oblog/value.replace(/[^\u4E00-\u9FA5]/g,'')">
3." 只能是英文
<script language=javascript>
function onlyEng()
{
if(!(event.keyCode>=65&&event.keyCode<=90))
JavaScript常用表单验证正则表达式(身份证、电话号码、邮编、日期、IP等)
JavaScript常⽤表单验证正则表达式(⾝份证、电话号码、邮编、⽇期、IP等)⾝份证正则表达式//⾝份证正则表达式(15位)isIDCard1=/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;//⾝份证正则表达式(18位)isIDCard2=/^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/;地区、性别和⾝份证进⾏判断的正则表达式:<script>varaCity={11:”北京”,12:”天津”,13:”河北”,14:”⼭西”,15:”内蒙古”,21:”辽宁”,22:”吉林”,23:”⿊龙江”,31:”上海”,32:”江苏”,33:”浙江”,34:”安徽”,35:”福建”,36:”江西”,37:”⼭东”,41:”河南”,42:”湖北”,43:”湖南”,44:”⼴东”,45:”⼴西”,46:”海南”,50:”重庆”,51:”四川”,52:”贵州”,53:”云南”,54:”西藏”,61:”陕西”,62:”⽢肃”,63:”青海”,64:”宁夏”,65:”新疆”,71:”台湾”,81:”⾹港”,82:”澳门”,91:”国外”}function cidInfo(sId){var iSum=0var info=”"if(!/^\d{17}(\d|x)$/i.test(sId))return false;sId=sId.replace(/x$/i,”a”);if(aCity[parseInt(sId.substr(0,2))]==null)return “Error:⾮法地区”;sBirthday=sId.substr(6,4)+”-”+Number(sId.substr(10,2))+”-”+Number(sId.substr(12,2));var d=new Date(sBirthday.replace(/-/g,”/”))if(sBirthday!=(d.getFullYear()+”-”+ (d.getMonth()+1) + “-” + d.getDate()))return “Error:⾮法⽣⽇”;for(var i = 17;i>=0;i –) iSum += (Math.pow(2,i) % 11) * parseInt(sId.charAt(17 – i),11)if(iSum%11!=1)return “Error:⾮法证号”;return aCity[parseInt(sId.substr(0,2))]+”,”+sBirthday+”,”+(sId.substr(16,1)%2?”男”:”⼥”)}</script>————-正则表达式全集中国电话号码验证匹配形式如:0511-******* 或者021-******** 或者 021-********-555 或者 (0511)4405222正则表达式 “((d{3,4})|d{3,4}-)?d{7,8}(-d{3})*”中国邮政编码验证匹配形式如:215421正则表达式 “d{6}”电⼦邮件验证匹配形式如:justali@正则表达式 “w+([-+.]w+)*@w+([-.]w+)*.w+([-.]w+)*”⾝份证验证匹配形式如:15位或者18位⾝份证正则表达式 “d{18}|d{15}”常⽤数字验证正则表达式“d{n}” n为规定长度“d{n,m}” n到m的长度范围⾮法字符验证匹配⾮法字符如:< > & / ‘ |正则表达式 [^<>&/|'\]+⽇期验证匹配形式如:20030718,030718范围:1900–2099正则表达式((((19){1}|(20){1})d{2})|d{2})[01]{1}d{1}[0-3]{1}d{1}正则表达式是⼀个好东西,但是⼀般情况下,我们需要验证的内容少之⼜少。
JS表单判断函数代码大全
}
if (j==0)
{
return 0;
}
if (i!=j)
{ return 2; }
else
{
return 1;
}
}
//函数名:chkemail
//功能介绍:检查是否为Email Address
//参数说明:要检查的字符串
//返回值:0:不是 1:是
var isNot=" !@#$^*()'`~|]}[{;.>,<?%&+=";
if (val2.indexOf('\"')>0){
alert("请输入正确的文件路径。");
val.focus();
val.select();
return false;
}
else{
for (var i = 0;i < val2.length;i++){
return false
}
else {
return true
}
}
}
//验证Zip
function CheckZip(val,slen,mode){
if((mode==0) && (val.value=="")){
return true;
}
if(val.value.length!=slen){
alert("请输入正确的URL。");
val.focus();
val.select();
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
js验证表单大全1. 长度限制<script>function test(){if(document.a.b.value.length>50){alert("不能超过50个字符!");document.a.b.focus();return false;}}</script><form name=a onsubmit="return test()"><textarea name="b" cols="40" wrap="VIRTUAL" rows="6"></textarea><input type="submit" name="Submit" value="check"></form>2. 只能是汉字<input onkeyup="value="/oblog/value.replace(/[^\u4E00-\u9FA5]/g,'')">3." 只能是英文<script language=javascript>function onlyEng(){if(!(event.keyCode>=65&&event.keyCode<=90))event.returnvalue=false;}</script><input onkeydown="onlyEng();">4. 只能是数字<script language=javascript>function onlyNum(){if(!((event.keyCode>=48&&event.keyCode<=57)||(event.keyCode>=96&&event.keyCode <=105)))//考虑小键盘上的数字键event.returnvalue=false;}</script><input onkeydown="onlyNum();">5. 只能是英文字符和数字<input onkeyup="value="/oblog/value.replace(/[\W]/g,"'')"onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[^\d]/ g,''))">6. 验证油箱格式<SCRIPT LANGUAGE=javascript RUNAT=Server>function isEmail(strEmail) {if(strEmail.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)return true;elsealert("oh");}</SCRIPT><input type=text onblur=isEmail(this.value)>7. 屏蔽关键字(这里屏蔽***和****)<script language="javascript1.2">function test() {if((a.b.value.indexOf ("***") == 0)||(a.b.value.indexOf ("****") == 0)){alert(":)");a.b.focus();return false;}}</script><form name=a onsubmit="return test()"><input type=text name=b><input type="submit" name="Submit" value="check"></form>8. 两次输入密码是否相同<FORM METHOD=POST ACTION=""><input type="password" id="input1"><input type="password" id="input2"><input type="button" value="test" onclick="check()"></FORM><script>function check(){with(document.all){if(input1.value!=input2.value)alert("false")input1.value = "";input2.value = "";}else document.forms[0].submit();}}</script>够了吧:)屏蔽右键很酷oncontextmenu="return false" ondragstart="return false" onselectstart="return false" 加在body中二2.1 表单项不能为空<script language="javascript"><!--function CheckForm(){if (.value.length == 0) {alert("请输入您姓名!");.focus();return false;}return true;}--></script>2.2 比较两个表单项的值是否相同<script language="javascript"><!--function CheckForm()if (document.form.PWD.value != document.form.PWD_Again.value) {alert("您两次输入的密码不一样!请重新输入.");document.ADDUser.PWD.focus();return false;}return true;--></script>2.3 表单项只能为数字和"_",用于电话/银行帐号验证上,可扩展到域名注册等<script language="javascript"><!--function isNumber(String){var Letters = "1234567890-"; //可以自己增加可输入值var i;var c;if(String.charAt( 0 )=='-')return false;if( String.charAt( String.length - 1 ) == '-' )return false;for( i = 0; i < String.length; i ++ ){c = String.charAt( i );if (Letters.indexOf( c ) < 0)return false;}return true;}function CheckForm(){if(! isNumber(document.form.TEL.value)) {alert("您的电话号码不合法!");document.form.TEL.focus();return false;}return true;}--></script>2.4 表单项输入数值/长度限定<script language="javascript"><!--function CheckForm(){if (document.form.count.value > 100 || document.form.count.value < 1) {alert("输入数值不能小于零大于100!");document.form.count.focus();return false;}if (document.form.MESSAGE.value.length<10){alert("输入文字小于10!");document.form.MESSAGE.focus();return false;}return true;}//--></script>2.5 中文/英文/数字/邮件地址合法性判断<SCRIPT LANGUAGE="javascript"><!--function isEnglish(name) //英文值检测{if(name.length == 0)return false;for(i = 0; i < name.length; i++) {if(name.charCodeAt(i) > 128)return false;}return true;}function isChinese(name) //中文值检测{if(name.length == 0)return false;for(i = 0; i < name.length; i++) {if(name.charCodeAt(i) > 128)return true;}return false;}function isMail(name) // E-mail值检测{if(! isEnglish(name))return false;i = name.indexOf(" at ");j = name dot lastIndexOf(" at ");if(i == -1)return false;if(i != j)return false;if(i == name dot length)return false;return true;}function isNumber(name) //数值检测{if(name.length == 0)return false;for(i = 0; i < name.length; i++) {if(name.charAt(i) < "0" || name.charAt(i) > "9") return false;}return true;}function CheckForm(){if(! isMail(form.Email.value)) {alert("您的电子邮件不合法!");form.Email.focus();return false;}if(! isEnglish(.value)) {alert("英文名不合法!");.focus();return false;}if(! isChinese(name.value)) {alert("中文名不合法!");name.focus();return false;}if(! isNumber(form.PublicZipCode.value)) {alert("邮政编码不合法!");form.PublicZipCode.focus();return false;}return true;}//--></SCRIPT>2.6 限定表单项不能输入的字符<script language="javascript"><!--function contain(str,charset)// 字符串包含测试函数{var i;for(i=0;i<charset.length;i++)if(str.indexOf(charset.charAt(i))>=0)return true;return false;}function CheckForm(){if ((contain(.value, "%\(\)><")) || (contain(document.form.ME SSAGE.value, "%\(\)><"))){alert("输入了非法字符");.focus();return false;}return true;}//--></script>1. 检查一段字符串是否全由数字组成---------------------------------------<script language="Javascript"><!--function checkNum(str){return str.match(/\D/)==null}alert(checkNum("1232142141"))alert(checkNum("123214214a1"))// --></script>2. 怎么判断是否是字符---------------------------------------if (/[^\x00-\xff]/g.test(s)) alert("含有汉字");else alert("全是字符");3. 怎么判断是否含有汉字---------------------------------------if (escape(str).indexOf("%u")!=-1) alert("含有汉字"); else alert("全是字符");4. 邮箱格式验证---------------------------------------//函数名:chkemail//功能介绍:检查是否为Email Address//参数说明:要检查的字符串//返回值:0:不是1:是function chkemail(a){ var i=a.length;var temp = a.indexOf('@');var tempd = a.indexOf('.');if (temp > 1) {if ((i-temp) > 3){if ((i-tempd)>0){return 1;}}}return 0;}5. 数字格式验证---------------------------------------//函数名:fucCheckNUM//功能介绍:检查是否为数字//参数说明:要检查的数字//返回值:1为是数字,0为不是数字function fucCheckNUM(NUM){var i,j,strTemp;strTemp="0123456789";if ( NUM.length== 0)return 0for (i=0;i<NUM.length;i++){j=strTemp.indexOf(NUM.charAt(i)); if (j==-1){//说明有字符不是数字return 0;}}//说明是数字return 1;}6. 电话号码格式验证---------------------------------------//函数名:fucCheckTEL//功能介绍:检查是否为电话号码//参数说明:要检查的字符串//返回值:1为是合法,0为不合法function fucCheckTEL(TEL){var i,j,strTemp;strTemp="0123456789-()# ";for (i=0;i<TEL.length;i++){j=strTemp.indexOf(TEL.charAt(i));if (j==-1){//说明有字符不合法return 0;}}//说明合法return 1;}7. 判断输入是否为中文的函数--------------------------------------- function ischinese(s){var ret=true;for(var i=0;i<s.length;i++)ret=ret && (s.charCodeAt(i)>=10000); return ret;}8. 综合的判断用户输入的合法性的函数---------------------------------------<script language="javascript">//限制输入字符的位数开始//m是用户输入,n是要限制的位数function issmall(m,n){if ((m<n) && (m>0)){return(false);}else{return(true);}}9. 判断密码是否输入一致---------------------------------------function issame(str1,str2){if (str1==str2){return(true);}else{return(false);}}10. 判断用户名是否为数字字母下滑线---------------------------------------function notchinese(str){var reg=/[^A-Za-z0-9_]/gif (reg.test(str)){return (false);}else{return(true); }}11. form文本域的通用校验函数---------------------------------------作用:检测所有必须非空的input文本,比如姓名,账号,邮件地址等等。