代码如下:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162 | <!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 > |
效果图如下: