---
title: "javaScript对只能输入某些特殊组合字符串的验证"
author: "jayzotion"
date: "2009-04-23T14:32:31Z"
tags: []
categories: ["Web前端"]
slug: "javascript"
draft: false
lastmod: "2009-04-24T08:53:43Z"
id: 373311
url: "https://jayzotion.iteye.com/blog/373311"
---

因工作需要，今天帮同事写了一个要求如下的前台js验证代码:
1)以数字,逗号,"-"三个符号组成
2)以数字开头和结尾.
3)"-"前后必须是数字

```java

<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)">



```