2016-08-19 54 views
-1

在我的文本框中,我只允许使用整数值和逗号来控制使用javascript.Now我怀疑如何控制比逗号连续(即)1,2,3,4是好吧然后1,2,3,,4,,5其需要restricted.Its可能在JavaScript中。多个逗号限制使用javascript

<p:inputText onKeyPress="onlyAllowDigitComma(event);"/> 
+0

可以提供onlyAllowDigitComma功能代码???? – Ruhul

+0

我们知道每个人都不是英语母语的人,但在这个意义上,标准的国际英语不使用“怀疑”,我们使用“问题”。另外,它在完全停止之后放置空格,并且在诸如“它是”(当“它是”的缩写)时使用单词中的撇号。该语言的正确大小写是“JavaScript”。 – 2016-08-19 10:16:05

回答

0

使用正则表达式来验证您的输入。如果你得到的第一场比赛与整个输入相同,那么你很好。

你正在寻找的正则表达式是/(\d,?)*/gTest Link

为了简单起见,我做了下面的代码与“KEYUP”事件,以避免快捷方式的问题。您可能还想检查复制/粘贴事件。

let myInput = document.getElementById('myInput'); 
let myInputValue = myInput.value; 

myInput.addEventListener('keyup', function(event){ 
    if(isPerfectMatch(myInput.value, /(\d,?)*/g)){ 
    console.log('Format is correct.'); 
    myInputValue = myInput.value; 
    } 
    else { 
    console.log('Wrong format'); 
    myInput.value = myInputValue; 
    } 
}); 

function isPerfectMatch(value, regex){ 
    let match = value.match(regex); 
    return match !== null && match[0] == value; 
} 

Demo JSFiddle

0

你的回答不显示你走多远与您的解决方案。我想代码咆哮是你想要的,我想你也需要从开始和结束时删除昏迷。

<input type="text" onkeypress="onlyAllowDigitComma(event,this);" onkeyup="onlyAllowDigitComma(event,this);"/> 
<script> 
function onlyAllowDigitComma(e,l){ 
    var k = e.which; 
    if ((k <= 47 || k >= 58) && k!=44 && k!=8 && k!=0) { 
     e.preventDefault() 
    }; 
    l.value=l.value.replace(/,,/g,','); 
} 
</script>