2016-08-19 21 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>