文章摘要
这篇文章介绍了使用JavaScript和jQuery实现的通用验证功能,包括手机号、身份证号和姓名的验证方法。文章提供了三个JavaScript函数:`isChinaName`用于验证姓名,`isCardNo`用于验证身份证号,以及`isPhoneNo`用于验证手机号。每个函数均通过jQuery绑定HTML元素,实现输入为空或无效时的错误提示功能,并通过焦点事件清空输入字段。文章还提醒用户在使用这些函数前需要引用jQuery库。
分享一段我用了很久的通用验证手机号/身份证/姓名代码,jQuery的,使用前记得引用jQuery哦。
都是使用的js函数的方法,调用方法都是函数名(ID)的方法,不懂可以看看JS函数教程。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
/*姓名身份证,手机号提交*/function isChinaName(name) { var pattern = /^[\u4E00-\u9FA5]{1,6}$/; return pattern.test(name);}// 验证身份证function isCardNo(card) { var pattern = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/; return pattern.test(card);}// 验证手机号function isPhoneNo(phone) { var pattern = /^1[34578]\d{9}$/; return pattern.test(phone);}/*用户名判断*/function userName(inputid, spanid) { $(inputid).blur(function() { if ($.trim($(inputid).val()).length == 0) { $(spanid).html("× 名称没有输入"); } else { if (isChinaName($.trim($(inputid).val())) == false) { $(spanid).html("× 名称不合法"); } } }); $(inputid).focus(function() { $(spanid).html(""); });};userName('#name', "#checkExistname");/*身份证判断*/function userID(inputid, spanid) { $(inputid).blur(function() { if ($.trim($(inputid).val()).length == 0) { $(spanid).html("× 身份证号码没有输入"); } else { if (isCardNo($.trim($(inputid).val())) == false) { $(spanid).html("× 身份证号不正确"); } } }); $(inputid).focus(function() { $(spanid).html(""); });};userID('#identity', "#checkExistID");/*手机号判断*/function userTel(inputid, spanid) { $(inputid).blur(function() { if ($.trim($(inputid).val()).length == 0) { $(spanid).html("× 手机号没有输入"); } else { if (isPhoneNo($.trim($(inputid).val())) == false) { $(spanid).html("× 手机号码不正确"); } } $(inputid).focus(function() { $(spanid).html(""); }); });};userTel('#telephone', "#checkExistPhone"); |
© 版权声明
文章版权归作者所有,未经允许请勿转载。