代碼如下:
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
|
<!DOCTYPE html> < html > < head > < meta charset = "UTF-8" > < title >實現JQuery限制輸入框僅接受特殊字符的輸入</ title > < link href = "css/style.css" rel = "stylesheet" > < script src = "js/jquery-1.9.1.js" type = "text/javascript" ></ script > </ head > < body > < div class = "box" > < h2 class = "h2-caption" > 實現JQuery限制輸入框僅接受特殊字符的輸入</ h2 > < hr >< br > < p >不允許輸入特殊字符和空格:< input id = "code" type = "text" name = "" value = "" onkeypress = "return ValidateSpecialCharacter();" onblur = "validate(this)" ></ p > < p >不允許輸入空格:< input type = "text" id = "dd" name = "" value = "" onkeyup = "value=value.replace(/\s/g,'')" ></ p > </ div > < script type = "text/javascript" > function ValidateSpecialCharacter(){ var code; if(document.all) { //判斷是否是IE瀏覽器 code = window.event.keyCode; }else{ code = arguments.callee.caller.arguments[0].which; } var character = String.fromCharCode(code); var txt=new RegExp("[ ,\\`,\\~,\\!,\\@,\#,\\$,\\%,\\^,\\+,\\*,\\&,\\\\,\\/,\\?,\\|,\\:,\\.,\\<,\\>,\\{,\},\\(,\\),\\'',\\;,\\=,\"]"); //特殊字符正則表達式 if(txt.test(character)){ if(document.all){ window.event.returnValue = false; }else{ arguments.callee.caller.arguments[0].preventDefault(); } } } // 驗證中文字符和特殊字符 function chineseVaildate(value){ if(value == null || value=="") return true; if((/[\u4E00-\u9FA5]+/.test(value))){ return false; } return true; } function validate(obj){ if(!chineseVaildate(obj.value)){ alert("有特殊字符和中文字符"); } } </ script > </ body > </ html > </ html > |
效果圖如下: