2010-07-12 13 views
0

我試着通過JS找出如果無效字符是在一個文本輸入檢查特定的字符寫,並觸發

我想只允許該字符的錯誤:

A-Za-z0-9 !#%&*()+-=,.?"';:/ 

如果非法字符輸入了,我要檢索的壞字符,並觸發一個錯誤,即:

文字無效,壞字符寫:

1) _ 
2) @ 
etc... 

謝謝!

+2

如果你確定與使用jQuery - http://stackoverflow.com/questions/2812585/jquery-validate-characters-on-keypress – potatopeelings 2010-07-12 10:04:22

+0

你想要做什麼檢查? – 2010-07-12 10:26:43

+0

我想做檢查提交 – WEBProject 2010-07-12 10:33:25

回答

2

我不確定你什麼時候想做這個檢查,但是這裏有一個檢查功能。它會提醒第一個無效字符。

function checkValue(input) { 
    var result = /[^a-z0-9 !#%&*()+\-=,.?"';:\/]/i.exec(input.value); 
    if (result) { 
     alert("Character '" + result[0] + "' is not allowed"); 
     return false; 
    } else { 
     return true; 
    } 
} 

如果你希望所有匹配的非有效字符,那麼你可以使用下列內容:

function checkValue(input) { 
    var isValid = true, result, matchedChars = []; 
    while((result = /[^a-z0-9 !#%&*()+\-=,.?"';:\/]/ig.exec(input.value))) { 
     matchedChars.push("'" + result[0] + "'"); 
     isValid = false; 
    } 
    if (!isValid) { 
     alert("Characters " + matchedChars.join(", ") + " are not allowed"); 
    } 
    return isValid; 
} 
+0

這個正則表達式不允許OP說他的空格 – 2010-07-12 11:00:20

+0

所以他這樣做,我錯過了,雖然我認爲在我開始寫答案之後,OP確實編輯了這個問題使之更加清晰,無論如何,現在已經修復了, – 2010-07-12 11:09:18

+0

你不需要在內部轉義點或量詞人物類 – SilentGhost 2010-07-12 11:10:39

相關問題