我在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'}
該警告非常明確。它告訴你,你在一個多行的正則表達式中使用錨點來開始和結束行,而不用說它會在單行上工作,在''上''A'優先於'^','\ z'優於'$'單行檢查。所以用'/ \ A([^ \ d \ W] | [ - ])* \ z /'形式的正則表達式可以工作,你可以在http://regex101.com上測試它,正則表達式的錨點/部分。 – Tensibai 2014-10-08 11:55:11
有關說明,請參閱http://guides.rubyonrails.org/security.html#regular-expressions – Stefan 2014-10-08 11:55:23