2014-10-08 105 views
1

我在Rails中設置了一個需要名和姓的用戶表單。我決定使用Ruby doc的第三個最後一個正則表達式來確保它們不輸入任何數字或特殊字符。不幸的是,當我返回到窗體我得到這個錯誤:排除數字或特殊字符的正則表達式

The provided regular expression is using multiline anchors (^ or $), which may present a security risk. Did you mean to use \A and \z, or forgot to add the :multiline => true option?.

我剛開始學習正則表達式,所以如果有寫這個驗證我所有的耳朵更好的辦法。

代碼:

validates :first_name, :last_name, length: {minimum: 2}, format: {with: /^([^\d\W]|[-])*$/, message: 'First Name/Last Name cannot have any numbers or special characters'} 
+0

該警告非常明確。它告訴你,你在一個多行的正則表達式中使用錨點來開始和結束行,而不用說它會在單行上工作,在''上''A'優先於'^','\ z'優於'$'單行檢查。所以用'/ \ A([^ \ d \ W] | [ - ])* \ z /'形式的正則表達式可以工作,你可以在http://regex101.com上測試它,正則表達式的錨點/部分。 – Tensibai 2014-10-08 11:55:11

+0

有關說明,請參閱http://guides.rubyonrails.org/security.html#regular-expressions – Stefan 2014-10-08 11:55:23

回答

4

您鏈接到狀態的文檔:

Note: use \A and \Z to match the start and end of the string,^and $ match the start/end of a line.

既然你不需要爲多名支持(即在名義換行符應被視爲無效),你可以安全地將其更改爲:還

/\A([^\d\W]|[-])*\Z/ 

this answer這也解釋了安全風險多一點。

1

您將需要使用\A線路的起點和\z線路,而不是^$的結束,由於安全方面的原因。所以,你的正則表達式應該是

/\A([^\d\W]|[-])*\z/