有用的正则验证,转自互联网

前端之家收集整理的这篇文章主要介绍了有用的正则验证,转自互联网前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
/*
用途:检查输入的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;
}

用途:校验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;
用途:检查输入手机号码是否正确
s:字符串
function checkMobile( s ){
var regu =/^[1][3][0-9]{9}$/;
var re = new RegExp(regu);
if (re.test(s)) {
用途:检查输入的电话号码格式是否正确
strPhone:字符串
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) ){
alert( prompt );
if( phoneRegNoArea.test( strPhone ) ){
用途:检查输入字符串是否为空或者全部都是空格
输入:str
如果全是空返回true,u5b8bu4f53; font-size:16px; line-height:28px">function isNull( str ){
if ( str == "" ) return true;
var regu = "^[ ]+$";
return re.test(str);
用途:检查输入对象的值是否符合整数格式
输入:str 输入的字符串
function isInteger( str ){
var regu = /^[-]{0,1}[0-9]{1,}$/;
return regu.test(str);
用途:检查输入字符串是否符合正整数格式
function isNumber( s ){
var regu = "^[0-9]+$";
if (s.search(re) != -1) {
} else {
用途:检查输入字符串是否是带小数的数字格式,可以是负数
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;
用途:检查输入对象的值是否符合端口号格式
function isPort( str ){
return (isNumber(str) && str<65536);
用途:检查输入字符串是否符合金额格式
格式定义为带小数的正数,小数点后最多三位
function isMoney( s ){
var regu = "^[0-9]+[\.][0-9]{0,3}$";
用途:检查输入字符串是否只由英文字母和数字和下划线组成
function isNumberOr_Letter( s ){//判断是否是数字或字母
var regu = "^[0-9a-zA-Z\_]+$";
用途:检查输入字符串是否只由英文字母和数字组成
function isNumberOrLetter( s ){//判断是否是数字或字母
var regu = "^[0-9a-zA-Z]+$";
用途:检查输入字符串是否只由汉字、字母、数字组成
value:字符串
function isChinaOrNumbOrLett( s ){//判断是否是汉字、字母、数字组成
var regu = "^[0-9a-zA-Z\u4e00-\u9fa5]+$";
用途:判断是否是日期
输入:date:日期;fmt:日期格式
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;
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";
else
return "28";
return "31";
用途:字符1是否以字符串2结束
输入:str1:字符串;str2:被包含的字符串
function isLastMatch(str1,str2)
var index = str1.lastIndexOf(str2);
if(str1.length==index+str2.length) return true;
用途:字符1是否以字符串2开始
function isFirstMatch(str1,u5b8bu4f53; font-size:16px; line-height:28px">var index = str1.indexOf(str2);
if(index==0) return true;
用途:字符1是包含字符串2
function isMatch(str1,u5b8bu4f53; font-size:16px; line-height:28px">if(index==-1) return false;
用途:检查输入的起止日期是否正确,规则为两个日期的格式正确,
且结束如期>=起始日期
startDate:起始日期,字符串
endDate:结束如期,字符串
function checkTwoDate( startDate,endDate ) {
if( !isDate(startDate) ) {
alert("起始日期不正确!");
} else if( !isDate(endDate) ) {
alert("终止日期不正确!");
} else if( startDate > endDate ) {
alert("起始日期不能大于终止日期!");
用途:检查复选框被选中的数目
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;
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;
totalCount++ ;
return totalCount;
function getFirstSelectedValue( checkBoxID ){
var value = null;
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;
value = document.all(checkBoxID).value;
return value;
function getFirstSelectedIndex( checkBoxID ){
var value = -2;
value = i;
value = -1;
function selectAll( checkBoxID,status ){
if( document.all(checkBoxID) == null)
return;
document.all(checkBoxID).item( i ).checked = status;
document.all(checkBoxID).checked = status;
function selectInverse( checkBoxID ) {
document.all(checkBoxID).item( i ).checked = !document.all(checkBoxID).item( i ).checked;
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")
var month = value.substring(4,6);
if(month>"12" || month< "01") return false;
var day = value.substring(6,8);
用途:检查输入的起止日期是否正确,规则为两个日期的格式正确或都为空
且结束日期>=起始日期
endDate: 结束日期,字符串
function checkPeriod( startDate,u5b8bu4f53; font-size:16px; line-height:28px">if( !checkDate(startDate) ) {
} else if( !checkDate(endDate) ) {
用途:检查证券代码是否正确
secCode:证券代码
function checkSecCode( secCode ) {
if( secCode.length !=6 ){
alert("证券代码长度应该为6位");
if(!isNumber( secCode ) ){
alert("证券代码只能包含数字");
function:cTrim(sInputString,iType)
description:字符串去空格的函数
parameters:iType:1=去掉字符串左边的空格
2=去掉字符串左边的空格
0=去掉字符串左边和右边的空格
return value:去掉空格的字符串
function cTrim(sInputString,u5b8bu4f53; font-size:16px; line-height:28px">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;
--i;
sInputString = sInputString.substring(0,i+1);
return sInputString;
Require : /.+/,
Email : /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/,u5b8bu4f53; font-size:16px; line-height:28px">Phone : /^((\(\d{2,3}\))|(\d{3}\-))?(\(0\d{2,3}\)|0\d{2,3}-)?[1-9]\d{6,8}(\-\d{1,5})?$/,u5b8bu4f53; font-size:16px; line-height:28px">Mobile : /^((\(\d{2,3}\))|(\d{3}\-))?13\d{9}$/,u5b8bu4f53; font-size:16px; line-height:28px">Url : /^http:\/\/[A-Za-z0-9]+\.[A-Za-z0-9]+[\/=\?%\-&_~`@[\]\':+!]*([^<>\"\"])*$/,u5b8bu4f53; font-size:16px; line-height:28px">IdCard : "this.IsIdCard(value)",u5b8bu4f53; font-size:16px; line-height:28px">Currency : /^\d+(\.\d+)?$/,u5b8bu4f53; font-size:16px; line-height:28px">Number : /^\d+$/,u5b8bu4f53; font-size:16px; line-height:28px">Zip : /^[1-9]\d{5}$/,u5b8bu4f53; font-size:16px; line-height:28px">QQ : /^[1-9]\d{4,8}$/,u5b8bu4f53; font-size:16px; line-height:28px">Integer : /^[-\+]?\d+$/,u5b8bu4f53; font-size:16px; line-height:28px">Double : /^[-\+]?\d+(\.\d+)?$/,u5b8bu4f53; font-size:16px; line-height:28px">English : /^[A-Za-z]+$/,u5b8bu4f53; font-size:16px; line-height:28px">Chinese : /^[\u0391-\uFFE5]+$/,u5b8bu4f53; font-size:16px; line-height:28px">Username : /^[a-z]\w{3,}$/i,u5b8bu4f53; font-size:16px; line-height:28px">UnSafe : /^(([A-Z]*|[a-z]*|\d*|[-_\~!@#\$%\^&\*\.\(\)\[\]\{\}<>\?\\\/\'\"]*)|.{0,5})$|\s/,u5b8bu4f53; font-size:16px; line-height:28px">IsSafe : function(str){return !this.UnSafe.test(str);},u5b8bu4f53; font-size:16px; line-height:28px">SafeString : "this.IsSafe(value)",u5b8bu4f53; font-size:16px; line-height:28px">Filter : "this.DoFilter(value,getAttribute('accept'))",u5b8bu4f53; font-size:16px; line-height:28px">Limit : "this.limit(value.length,getAttribute('min'),getAttribute('max'))",u5b8bu4f53; font-size:16px; line-height:28px">LimitB : "this.limit(this.LenB(value),u5b8bu4f53; font-size:16px; line-height:28px">Date : "this.IsDate(value,getAttribute('format'))",u5b8bu4f53; font-size:16px; line-height:28px">Repeat : "value == document.getElementsByName(getAttribute('to'))[0].value",u5b8bu4f53; font-size:16px; line-height:28px">Range : "getAttribute('min') < (value|0) && (value|0) < getAttribute('max')",u5b8bu4f53; font-size:16px; line-height:28px">Compare : "this.compare(value,getAttribute('operator'),getAttribute('to'))",u5b8bu4f53; font-size:16px; line-height:28px">Custom : "this.Exec(value,getAttribute('regexp'))",u5b8bu4f53; font-size:16px; line-height:28px">Group : "this.MustChecked(getAttribute('name'),u5b8bu4f53; font-size:16px; line-height:28px">ErrorItem : [document.forms[0]],u5b8bu4f53; font-size:16px; line-height:28px">ErrorMessage : ["以下原因导致提交失败:\t\t\t\t"],u5b8bu4f53; font-size:16px; line-height:28px">Validate : function(theForm,mode){
var obj = theForm || event.srcElement;
var count = obj.elements.length;
this.ErrorMessage.length = 1;
this.ErrorItem.length = 1;
this.ErrorItem[0] = obj;
for(var i=0;i<count;i++){
with(obj.elements[i]){
var _dataType = getAttribute("dataType");
if(typeof(_dataType) == "object" || typeof(this[_dataType]) == "undefined") continue;
this.ClearState(obj.elements[i]);
if(getAttribute("require") == "false" && value == "") continue;
switch(_dataType){
case "IdCard" :
case "Date" :
case "Repeat" :
case "Range" :
case "Compare" :
case "Custom" :
case "Group" :
case "Limit" :
case "LimitB" :
case "SafeString" :
case "Filter" :
if(!ev al(this[_dataType])) {
this.AddError(i,getAttribute("msg"));
default :
if(!this[_dataType].test(value)){
if(this.ErrorMessage.length > 1){
mode = mode || 1;
var errCount = this.ErrorItem.length;
switch(mode){
case 2 :
for(var i=1;i<errCount;i++)
this.ErrorItem[i].style.color = "red";
case 1 :
alert(this.ErrorMessage.join("\n"));
try{
if(this.ErrorItem[1].type!="hidden")
this.ErrorItem[1].focus();
}catch(e){}
case 3 :
for(var i=1;i<errCount;i++){
var span = document.createElement("SPAN");
span.id = "__ErrorMessagePanel";
span.style.color = "red";
this.ErrorItem[i].parentNode.appendChild(span);
span.innerHTML = this.ErrorMessage[i].replace(/\d+:/,"*");
catch(e){alert(e.description);}
},u5b8bu4f53; font-size:16px; line-height:28px">limit : function(len,min,max){
min = min || 0;
max = max || Number.MAX_VALUE;
return min <= len && len <= max;
LenB : function(str){
return str.replace(/[^\x00-\xff]/g,"**").length;
ClearState : function(elem){
with(elem){
if(style.color == "red")
style.color = "";
var lastNode = parentNode.childNodes[parentNode.childNodes.length-1];
if(lastNode.id == "__ErrorMessagePanel")
parentNode.removeChild(lastNode);
AddError : function(index,str){
this.ErrorItem[this.ErrorItem.length] = this.ErrorItem[0].elements[index];
this.ErrorMessage[this.ErrorMessage.length] = this.ErrorMessage.length + ":" + str;
Exec : function(op,reg){
return new RegExp(reg,"g").test(op);
compare : function(op1,operator,op2){
switch (operator) {
case "NotEqual":
return (op1 != op2);
case "GreaterThan":
return (op1 > op2);
case "GreaterThanEqual":
return (op1 >= op2);
case "LessThan":
return (op1 < op2);
case "LessThanEqual":
return (op1 <= op2);
default:
return (op1 == op2);
MustChecked : function(name,u5b8bu4f53; font-size:16px; line-height:28px">var groups = document.getElementsByName(name);
var hasChecked = 0;
min = min || 1;
max = max || groups.length;
for(var i=groups.length-1;i>=0;i--)
if(groups[i].checked) hasChecked++;
return min <= hasChecked && hasChecked <= max;
DoFilter : function(input,filter){
return new RegExp("^.+\.(?=EXT)(EXT)$".replace(/EXT/g,filter.split(/\s*,\s*/).join("|")),"gi").test(input);
IsIdCard : function(number){
var date,Ai;
var verify = "10x98765432";
var Wi = [7,9,10,5,8,4,2,1,6,3,7,2];
var area = ['','','北京','天津','河北','山西','内蒙古','辽宁','吉林','黑龙江','上海','江苏','浙江','安微','福建','江西','山东','河南','湖北','湖南','广东','广西','海南','重庆','四川','贵州','云南','西藏','陕西','甘肃','青海','宁夏','新疆','台湾','香港','澳门','国外'];
var re = number.match(/^(\d{2})\d{4}(((\d{2})(\d{2})(\d{2})(\d{3}))|((\d{4})(\d{2})(\d{2})(\d{3}[x\d])))$/i);
if(re == null) return false;
if(re[1] >= area.length || area[re[1]] == "") return false;
if(re[2].length == 12){
Ai = number.substr(0,17);
date = [re[9],re[10],re[11]].join("-");
else{

date = ["19" + re[4],re[5],re[6]].join("-");
if(!this.IsDate(date,"ymd")) return false;
var sum = 0;
for(var i = 0;i<=16;i++){
sum += Ai.charAt(i) * Wi[i];
Ai += verify.charAt(sum%11);
return (number.length ==15 || number.length == 18 && number == Ai);
IsDate : function(op,formatString){
formatString = formatString || "ymd";
var m,year,month,day;
switch(formatString){
case "ymd" :
m = op.match(new RegExp("^((\\d{4})|(\\d{2}))([-./])(\\d{1,2})\\4(\\d{1,2})$"));
if(m == null ) return false;
day = m[6];
month = m[5]*1;
year = (m[2].length == 4) ? m[2] : GetFullYear(parseInt(m[3],10));
case "dmy" :
m = op.match(new RegExp("^(\\d{1,2})([-./])(\\d{1,2})\\2((\\d{4})|(\\d{2}))$"));
day = m[1];
month = m[3]*1;
year = (m[5].length == 4) ? m[5] : GetFullYear(parseInt(m[6],u5b8bu4f53; font-size:16px; line-height:28px">if(!parseInt(month)) return false;
month = month==0 ?12:month;
var date = new Date(year,month-1,day);
return (typeof(date) == "object" && year == date.getFullYear() && month == (date.getMonth()+1) && day == date.getDate());
function GetFullYear(y){return ((y<30 ? "20" : "19") + y)|0;}
} 原文链接:https://www.f2er.com/regex/362318.html

猜你在找的正则表达式相关文章