js验证网址等Javascript常见验证代码合集

发一个利用js验证网址是否正确,email格式是否正确,是否为数字及数字的范围,密码或字符长度及是否相等及要求的最小字符串长度,输入是否为空等Javascript常见验证代码合集,用的上的朋友可以拿去了自行添加整理。

关键的JavaScript代码函数:

001 /**
002 * 数据验证框架.增加了对id字段检查出错时,直接在对应后面添加一< span>元素来显示错误信息.
003 *
004 * @author www.phpernote.com
005 * @version 1.0
006 * @description 2012-05-16
007 */
008 var checkData=new function(){
009 var idExt="_phpernote_Span";//生成span层的id后缀
010 /**
011 * 得到中英文字符长(中文为2个字符)
012 *
013 * @param {}
014 * str
015 * @return 字符长
016 */
017 this.length=function(str){
018     var p1=new RegExp('%u..''g');
019     var p2=new RegExp('%.''g');
020     return escape(str).replace(p1, '').replace(p2, '').length;
021 }
022 /**
023 * 删除对应id元素
024 */
025 this.remove=function(id){
026     var idObject=document.getElementById(id);
027     if(idObject != null)
028     idObject.parentNode.removeChild(idObject);
029 }
030 /**
031 * 在对应id后面错误信息
032 *
033 * @param id:需要显示错误信息的id元素
034 * str:显示错误信息
035 */
036 this.appendError=function(id, str){
037     this.remove(id + idExt);// 如果span元素存在,则先删除此元素
038     var spanNew=document.createElement("span");// 创建span
039     spanNew.id=id + idExt;// 生成spanid
040     spanNew.style.color="red";
041     spanNew.appendChild(document.createTextNode(str));// 给span添加内容
042     var inputId=document.getElementById(id);
043     inputId.parentNode.insertBefore(spanNew, inputId.nextSibling);// 给需要添加元素后面添加span
044 }
045 /**
046 * @description 过滤所有空格字符。
047 * @param str:需要去掉空间的原始字符串
048 * @return 返回已经去掉空格的字符串
049 */
050 this.trimSpace=function(str){
051     str+='';
052     while ((str.charAt(0) == ' ') || (str.charAt(0) == '???') || (escape(str.charAt(0)) == '%u3000'))
053     str=str.substring(1, str.length);
054     while ((str.charAt(str.length - 1) == ' ') || (str.charAt(str.length - 1) == '???') || (escape(str.charAt(str.length - 1)) == '%u3000'))
055     str=str.substring(0, str.length - 1);
056     return str;
057 }
058 /**
059 * 过滤字符串开始部分的空格\字符串结束部分的空格\将文字中间多个相连的空格变为一个空格
060 *
061 * @param {Object}
062 * inputString
063 */
064 this.trim=function(inputString){
065     if(typeof inputString != "string"){
066         return inputString;
067     }
068     var retValue=inputString;
069     var ch=retValue.substring(0, 1);
070     while (ch == " "){
071         // 检查字符串开始部分的空格
072         retValue=retValue.substring(1, retValue.length);
073         ch=retValue.substring(0, 1);
074     }
075     ch=retValue.substring(retValue.length - 1, retValue.length);
076     while (ch == " "){
077         // 检查字符串结束部分的空格
078         retValue=retValue.substring(0, retValue.length - 1);
079         ch=retValue.substring(retValue.length - 1, retValue.length);
080     }
081     while (retValue.indexOf(" ") != -1){
082         // 将文字中间多个相连的空格变为一个空格
083         retValue=retValue.substring(0, retValue.indexOf(" ")) + retValue.substring(retValue.indexOf(" ") + 1, retValue.length);
084     }
085     return retValue;
086 }
087 /**
088 * 过滤字符串,指定过滤内容,如果内容为空,则默认过滤 '~!@#$%^&*()-+."
089 *
090 * @param {Object}
091 * str
092 * @param {Object}
093 * filterStr
094 *
095 * @return 包含过滤内容,返回True,否则返回false;
096 */
097 this.filterStr=function(str, filterString){
098     filterString=filterString == "" "'~!@#$%^&*()-+.\"" : filterString;
099     var ch;
100     var i;
101     var temp;
102     var error=false;// 当包含非法字符时,返回True
103     for (i=0;i <= (filterString.length - 1);i++){
104         ch=filterString.charAt(i);
105         temp=str.indexOf(ch);
106         if(temp != -1){
107             error=true;
108             break;
109         }
110     }
111     return error;
112 }
113 this.filterStrSpan=function(id, filterString){
114     filterString=filterString == "" "'~!@#$%^&*()-+.\"" : filterString;
115     var val=document.getElementById(id);
116     if(this.filterStr(val.value, filterString)){
117         val.select();
118         var str="不能包含非法字符" + filterString;
119         this.appendError(id, str);
120         return false;
121     }else{
122         this.remove(id + idExt);
123         return true;
124     }
125 }
126 /**
127 * 检查是否为网址
128 *
129 * @param {}
130 * str_url
131 * @return {Boolean}true:是网址,false:<b>不是</b>网址;
132 */
133 this.isURL=function(str_url) {// 验证url
134     var strRegex="^((https|http|ftp|rtsp|mms)?://)"
135     "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" // ftp的user@
136     "(([0-9]{1,3}\.){3}[0-9]{1,3}" // IP形式的URL- 199.194.52.184
137     "|" // 允许IP和DOMAIN(域名)
138     "([0-9a-z_!~*'()-]+\.)*" // 域名- www.
139     "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." // 二级域名
140     "[a-z]{2,6})" // first level domain- .com or .museum
141     "(:[0-9]{1,4})?" // 端口- :80
142     "((/?)|" // a slash isn't required if there is no file name
143     "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$";
144     var re=new RegExp(strRegex);
145     return re.test(str_url);
146 }
147 this.isURLSpan=function(id){
148     var val=document.getElementById(id);
149     if(!this.isURL(val.value)){
150         val.select();
151         var str="链接不符合格式;";
152         this.appendError(id, str);
153         return false;
154     }else{
155         this.remove(id + idExt);
156         return true;
157     }
158 }
159 /**
160 * 检查是否为电子邮件
161 *
162 * @param {}
163 * str
164 * @return {Boolean}true:电子邮件,false:<b>不是</b>电子邮件;
165 */
166 this.isEmail=function(str){
167     var re=/^([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\-|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
168     return re.test(str);
169 }
170 this.isEmailSpan=function(id){
171     var val=document.getElementById(id);
172     if(!this.isEmail(val.value)){
173         val.select();
174         var str="邮件不符合格式;";
175         this.appendError(id, str);
176         return false;
177     }else{
178         this.remove(id + idExt);
179         return true;
180     }
181 }
182 /**
183 * 检查是否为数字
184 *
185 * @param {}
186 * str
187 * @return {Boolean}true:数字,false:<b>不是</b>数字;
188 */
189 this.isNum=function(str){
190     var re=/^[\d]+$/;
191     return re.test(str);
192 }
193 this.isNumSpan=function(id){
194     var val=document.getElementById(id);
195     if(!this.isNum(val.value)){
196         val.select();
197         var str="必须是数字;";
198         this.appendError(id, str);
199         return false;
200     }else{
201         this.remove(id + idExt);
202         return true;
203     }
204 }
205 /**
206 * 检查数值是否在给定范围以内,为空,不做检查<br>
207 *
208 * @param {}
209 * str_num
210 * @param {}
211 * small 应该大于或者等于的数值(此值为空时,只检查不能大于最大值)
212 * @param {}
213 * big 应该小于或者等于的数值(此值为空时,只检查不能小于最小值)
214 *
215 * @return {Boolean}<b>小于最小数值或者大于最大数值</b>数字返回false 否则返回true;
216 */
217 this.isRangeNum=function(str_num, small, big){
218     if(!this.isNum(str_num)) // 检查是否为数字
219     return false;
220     if(small == "" && big == "")
221     throw str_num + "没有定义最大,最小值数字!";
222     if(small != ""){
223         if(str_num < small)
224         return false;
225     }
226     if(big != ""){
227         if(str_num > big)
228         return false;
229     }
230     return true;
231 }
232 this.isRangeNumSpan=function(id, small, big){
233     var val=document.getElementById(id);
234     if(!this.isRangeNum(val.value, small, big)){
235         val.select();
236         var str="";
237         if(small != ""){
238             str="应该大于或者等于 " + small;
239         }
240         if(big != ""){
241             str+=" 应该小于或者等于 " + big;
242         }
243         this.appendError(id, str);
244         return false;
245     }else{
246         this.remove(id + idExt);
247         return true;
248     }
249 }
250 /**
251 * 检查是否为合格字符串(不区分大小写)<br>
252 * 是由a-z0-9_组成的字符串
253 *
254 * @param {}
255 * str 检查的字符串
256 * @param {}
257 * idStr 光标定位的字段ID<b>只能接收ID</b>
258 * @return {Boolean}<b>不是</b>"a-z0-9_"组成返回false,否则返回true;
259 */
260 this.isLicit=function(str){
261     var re=/^[_0-9a-zA-Z]*$/;
262     return re.test(str);
263 }
264 this.isLicitSpan=function(id){
265     var val=document.getElementById(id);
266     if(!this.isLicit(val.value)){
267         val.select();
268         var str="是由a-z0-9_组成的字符串(不区分大小写);";
269         this.appendError(id, str);
270         return false;
271     }else{
272         this.remove(id + idExt);
273         return true;
274     }
275 }
276 /**
277 * 检查二个字符串是否相等
278 *
279 * @param {}
280 * str1 第一个字符串
281 * @param {}
282 * str2 第二个字符串
283 * @return {Boolean}字符串不相等返回false,否则返回true;
284 */
285 this.isEquals=function(str1, str2){
286     return str1 == str2;
287 }
288 this.isEqualsSpan=function(id, id1){
289     var val=document.getElementById(id);
290     var val1=document.getElementById(id1);
291     if(!this.isEquals(val.value, val1.value)){
292         val.select();
293         var str="二次输入内容必须一样;";
294         this.appendError(id, str);
295         return false;
296     }else{
297         this.remove(id + idExt);
298         return true;
299     }
300 }
301 /**
302 * 检查字符串是否在给定长度范围以内(中文字符以2个字节计算),字符为空,不做检查<br>
303 *
304 * @param {}
305 * str 检查的字符
306 * @param {}
307 * lessLen 应该大于或者等于的长度
308 * @param {}
309 * moreLen 应该小于或者等于的长度
310 *
311 * @return {Boolean}<b>小于最小长度或者大于最大长度</b>数字返回false;
312 */
313 this.isRange=function(str, lessLen, moreLen){
314     var strLen=this.length(str);
315     if(lessLen != ""){
316     if(strLen < lessLen)
317         return false;
318     }
319     if(moreLen != ""){
320         if(strLen > moreLen)
321         return false;
322     }
323     if(lessLen == "" && moreLen == "")
324     throw "没有定义最大最小长度!";
325     return true;
326 }
327 this.isRangeSpan=function(id, lessLen, moreLen){
328     var val=document.getElementById(id);
329     if(!this.isRange(val.value, lessLen, moreLen)){
330         var str="长度";
331         if(lessLen != "")
332             str+="大于或者等于 " + lessLen + ";";
333         if(moreLen != "")
334             str+=" 应该小于或者等于 " + moreLen;
335         val.select();
336         this.appendError(id, str);
337         return false;
338     }else{
339         this.remove(id + idExt);
340         return true;
341     }
342 }
343 /**
344 * 检查字符串是否小于给定长度范围(中文字符以2个字节计算)<br>
345 *
346 * @param {}
347 * str 字符串
348 * @param {}
349 * lessLen 小于或等于长度
350 *
351 * @return {Boolean}<b>小于给定长度</b>数字返回false;
352 */
353 this.isLess=function(str, lessLen){
354     return this.isRange(str, lessLen, "");
355 }
356 this.isLessSpan=function(id, lessLen){
357     var val=document.getElementById(id);
358     if(!this.isLess(val.value, lessLen)){
359         var str="长度大于或者等于 " + lessLen;
360         val.select();
361         this.appendError(id, str);
362         return false;
363     }else{
364         this.remove(id + idExt);
365         return true;
366     }
367 }
368 /**
369 * 检查字符串是否大于给定长度范围(中文字符以2个字节计算)<br>
370 *
371 * @param {}
372 * str 字符串
373 * @param {}
374 * moreLen 小于或等于长度
375 *
376 * @return {Boolean}<b>大于给定长度</b>数字返回false;
377 */
378 this.isMore=function(str, moreLen){
379     return this.isRange(str, '', moreLen);
380 }
381 this.isMoreSpan=function(id, moreLen){
382     var val=document.getElementById(id);
383     if(!this.isMore(val.value, moreLen)){
384         var str="长度应该小于或者等于 " + moreLen;
385         val.select();
386         this.appendError(id, str);
387         return false;
388     }else{
389         this.remove(id + idExt);
390         return true;
391     }
392 }
393 /**
394 * 检查字符不为空
395 *
396 * @param {}
397 * str
398 * @return {Boolean}<b>字符为空</b>返回true,否则为false;
399 */
400 this.isEmpty=function(str){
401     return str == '';
402 }
403 this.isEmptySpan=function(id){
404     var val=document.getElementById(id);
405     if(this.isEmpty(val.value)){
406         var str="不允许为空;";
407         val.select();
408         this.appendError(id, str);
409         return false;
410     }else{
411         this.remove(id + idExt);
412         return true;
413     }
414     }
415 }

具体使用方法见下面案例:

01 <html>
02 <head>
03 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
04 <title>js验证网址,js验证email,js验证数字,js验证密码,js验证字符长度及是否相等,js验证数字范围,js验证是否为空等Javascript验证代码合集(www.phpernote.com)</title>
05 <script type="text/javascript" src="function.js"></script>
06 <script type="text/javascript">
07 function checkForm(){
08 var isPass = true;
09 //过滤字符串
10 if(!(checkData.isEmptySpan("filterStr") && checkData.filterStrSpan('filterStr','#$%$'))) {
11 isPass = false;
12 }
13 //检查url
14 if(!(checkData.isEmptySpan("isURL") && checkData.isURLSpan('isURL')))
15 isPass = false;
16 //email
17 if(!(checkData.isEmptySpan("isEmail") && checkData.isEmailSpan('isEmail')))
18 isPass = false;
19 //数字
20 if(!(checkData.isNumSpan('isNum')))
21 isPass = false;
22 //数字大小
23 if(!(checkData.isEmptySpan("isRangeNum") && checkData.isNumSpan('isRangeNum') && checkData.isRangeNumSpan('isRangeNum',10,100)))
24 isPass = false;
25 //密码 (数字,字母,下划线)
26 if(!(checkData.isLicitSpan('isLicit')))
27 isPass = false;
28 //二个字段是否相等
29 if(!(checkData.isEmptySpan("isEquals") && checkData.isEqualsSpan('isEquals','isEquals1')))
30 isPass = false;
31 //字符长度控制
32 if(!(checkData.isRangeSpan('isRange',5,10)))
33 isPass = false;
34 //字符最短控制
35 if(!(checkData.isLessSpan('isLess',10)))
36 isPass = false;
37 //字符最长控制
38 if(!(checkData.isEmptySpan("isMore") && checkData.isMoreSpan('isMore',30)))
39 isPass = false;
40 //为空控制
41 if(!(checkData.isEmptySpan("isEmpty")))
42 isPass = false;
43 return isPass;
44 }
45 </script>
46 </head>
47 <body>
48 <form action="index.jsp" method="post" onsubmit="return checkForm();">
49 <table>
50 <tbody>
51 <tr>
52 <td>字符过滤:<input type="text" id="filterStr" name="filterStr"></td>
53 <td>链接:<input type="text" id="isURL" name="isURL"></td>
54 </tr>
55 <tr>
56 <td>邮件:<input type="text" id="isEmail" name="isEmail"></td>
57 <td>数字:<input type="text" id="isNum" name="isNum"></td>
58 </tr>
59 <tr>
60 <td>数字范围:<input type="text" id="isRangeNum" name="isRangeNum"></td>
61 <td>a-zA-Z0-9_<input type="text" id="isLicit" name="isLicit"></td>
62 </tr>
63 <tr>
64 <td>判断相等:<input type="text" id="isEquals" name="isEquals"></td>
65 <td><input type="text" id="isEquals1" name="isEquals1"></td>
66 </tr>
67 <tr>
68 <td>长度控制:<input type="text" id="isRange" name="isRange"></td>
69 <td>长度大于控制:<input type="text" id="isLess" name="isLess"></td>
70 </tr>
71 <tr>
72 <td>长度小于控制:<input type="text" id="isMore" name="isMore"></td>
73 <td>是否为空:<input type="text" id="isEmpty" name="isEmpty"></td>
74 </tr>
75 <tr>
76 <td><input type="submit" name="submit" value="提交数据"></td>
77 </tr>
78 </tbody>
79 </table>
80 </form>
81 </body>
82 </html>
posted @ 2015-10-09 17:53  沃哥  阅读(1348)  评论(0编辑  收藏  举报