jquery 驗證非常簡單,下面總結常用的三種方式:
第一種方式:也是比較標准的方式:
首先引入jquery 插件和 jquery 驗證插件:
第一步:引入插件
代碼如下:
jquery驗證,需要有:
1:定義驗證方法
2:添加驗證規則
下面貼出常用的驗證小例子,一看就明白了。
先看效果圖:
? 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 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <script type="text/javascript" src="js/jquery-1.6.1.min.js"></script> <script type="text/javascript" src="js/jquery.validate.js"></script> <script type="text/javascript" src="js/jquery.metadata.js"></script> <script type="text/javascript" src="js/messages_zh.js"></script> <style type="text/css"> #frm label.error { color: Red; } </style> </head> <script type="text/javascript"> $(document).ready(function(){ $("#clickme").click(function(){ alert("Hello World"); }); $( "#frm" ).validate({ rules: { username: { required: true, minlength: 4, maxlength: 20, byteMaxLength:20, valiEnglish:true }, postcode: { postcodeVal:true }, number: { byteMaxLength:5, numFormat:5 }, identifier: { sfzhValidate:true } }, messages: { username: { required: "請輸入用戶名4--20個英文字符", minlength: $.format("Keep typing, at least {0} characters required!"), maxlength: $.format("Whoa! Maximum {0} characters allowed!") }, number: { numFormat: $.format("請輸入{0}數字") } } }); jQuery.validator.addMethod("byteMaxLength", function(value, element, param) { var length = value.length; for ( var i = 0; i < value.length; i++) { if (value.charCodeAt(i) > 127) { length++; } } return this.optional(element) || (length <= param); }, $.validator.format("不能超過{0}個字節(一個中文字算2個字節)")); jQuery.validator.addMethod("numFormat",function(value,element,param){ return this.optional(element) || /^d*$/.test(value); } //,$.validator.format("請輸入數字{0}位以內") ); //number(9,3) jQuery.validator.addMethod("numFormat63",function(value,element){ return this.optional(element) || /^[0-9]{1,6}(.d{1,3})$/.test(value); },$.validator.format("請輸入合法數字,精度格式123456.0") ); jQuery.validator.addMethod("postcodeVal",function(value,element){ return this.optional(element) || /^[0-9]d{5}(?!d)$/.test(value); },$.validator.format("請輸入合法的郵編") ); jQuery.validator.addMethod("numberAndLettersVal",function(value,element){ return this.optional(element) || /^[a-zA-Z0-9]+$/.test(value); },$.validator.format("請輸入字母或數字") ); jQuery.validator.addMethod("sfzhValidate",function(value,element){ return this.optional(element) || /^(d{14}