javaScript对只能输入某些特殊组合字符串的验证
因工作需要,今天帮同事写了一个要求如下的前台js验证代码:
1)以数字,逗号,"-"三个符号组成
2)以数字开头和结尾.
3)"-"前后必须是数字
<script type="text/javaScript">/**********only be some special char;*/function onlySomeChar(inputStr){if((inputStr.match(/^\d.*\d$/g) && (inputStr.search(/[^0-9,-]/g)==-1)) || inputStr.match(/^\d*$/)){for(var i =0;i<inputStr.toString().length;i++){if(inputStr.charAt(i)=="-"){if(isInt(inputStr.charAt(i-1))==false || isInt(inputStr.charAt(i+1))==false)return false;}}return true;}return false;}/***if Integer return true *else return false;*/function isInt(str){if (str.search(/[^0-9]/g)!=-1){return false;}return true;}//the function of testfunction test(strIn){if(onlySomeChar(strIn)==false){alert(0);}else{alert(1);}}</script><input type="text" id="test" onchange="test(this.value)">function test(obj){ if(obj.value.match(/^(\d{1,}[\d \- \,]?\d{1,})+$/)){ alert(1); }else{ alert(0); }}