2011-10-31 70 views

回答

9

您需要使用否定字符类。

[^A-Za-z0-9\-_] 

例:与match function一起使用以下模式

var notValid = 'This text should not be valid?'; 

if (notValid.match(/[^A-Za-z0-9\-_]/)) 
    alert('The text you entered is not valid.'); 
+0

那就是模式,但是我可以使用什么Javascript方法?谢谢 –

+1

或等同地,'[^ \ w \ - ]' –

+0

@John:阅读文档。 https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions和http://www.regular-expressions.info/javascript.html –

3

这一个很简单:

if (/[^\w\-]/.test(string)) { 
    alert("Unwanted character in input"); 
} 

的想法是,如果输入中包含甚至一个禁止的性格,你警报。

+0

只是为了澄清像我这样的人:'/ [^ \ w \ - ] /' - 这包含白名单,意思是允许的字符列表。添加一些东西到它后面,例如像这样:'/ [^ \ w \-äÖÖÖ] /'。 – Nenotlep