因工作需要,今天帮同事写了一个要求如下的前台js验证代码:
1)以数字,逗号,"-"三个符号组成
2)以数字开头和结尾.
3)"-"前后必须是数字
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 test
function test(strIn)
{
if(onlySomeChar(strIn)==false)
{
alert(0);
}
else
{
alert(1);
}
}
</script>
<input type="text" id="test" onchange="test(this.value)">