2013-04-08 75 views
1

我試圖用JavaScript中的正則表達式驗證字符串。該字符串可以有:正則表達式允許單詞字符,括號,空格和連字符

  • 字字符
  • 括號
  • 空間
  • 連字符( - )
  • 3至50長度

這裏是我的嘗試:

function validate(value, regex) { 
    return value.toString().match(regex); 
} 

validate(someString, '^[\w\s/-/(/)]{3,50}$'); 
+2

轉義字符在正則表達式是''\''不''/' '。而且,由於您使用的是字符串,因此您必須自行轉義''''(或讓您的生活變得輕鬆並使用正則表達式)。 – 2013-04-08 15:30:40

+0

是的,如果你使用正確的escape felix,你當前的正則表達式工作正常 – smerny 2013-04-08 15:31:50

+0

你知道'\ w'定義的單詞字符包括'A-Za-z0-9'和下劃線'_',對吧? – nhahtdh 2013-04-08 15:31:57

回答

5

寫您的驗證這樣

function validate(value, re) { 
    return re.test(value.toString()); 
} 

,並使用此正則表達式

/^[\w() -]{3,50}$/ 

一些測試

// spaces 
validate("hello world yay spaces", /^[\w() -]{3,50}$/); 
true 

// too short 
validate("ab", /^[\w() -]{3,50}$/); 
false 

// too long 
validate("this is just too long we need it to be shorter than this, ok?", /^[\w() -]{3,50}$/); 
false 

// invalid characters 
validate("you're not allowed to use crazy $ymbols", /^[\w() -]{3,50}$/); 
false 

// parentheses are ok 
validate("(but you can use parentheses)", /^[\w() -]{3,50}$/); 
true 

// and hyphens too 
validate("- and hyphens too", /^[\w() -]{3,50}$/); 
true 
+2

此外,如果你只是想驗證,'RegExp.test()'可能是一個更好的選擇,然後'String.match()'。 – 2013-04-08 15:33:46

+0

在這個答案中,你看到'str#match'?我在'validate'方法中使用're#test'。 – 2013-04-08 19:26:24

+0

這是在問題:'返回value.toString()。匹配(正則表達式);'。 – 2013-04-08 20:37:46

相關問題