2015-04-03 43 views
1

假設我有'城市'或'國家'輸入字段。 如何驗證此字段僅包含字母?如何驗證字段僅包含字母?

目前我有這樣一個空格替換任何最終的數字字符:

def strip_numeric_characters 
    self.city = self.city.gsub(/[0-9]/, "") 
    self.country = self.country.gsub(/[0-9]/, "") 
end 

但它不是正確的方式,因爲如果有人只輸入數字,我會帶空字符串結束。

回答

6

您可以驗證使用validates_format_of這樣的屬性格式:

validates_format_of :city, :country, :with => /^[a-z]+$/i 

/^[a-z]+$/i將只允許只包含字母城市和國家的名稱。以下是正則表達式的細節。

^  => Start of line 
[a-z] => Any single character in the range a-z 
+  => One or more characters of the range 
$  => End of line 
i  => To make case insensitive 
+0

作品只輸入數字時,但仍然節省了混合輸入像Netherlands2例如 – 2015-04-03 08:48:20

+0

所以,你只需要字母,它沒有數值,對不對? – 2015-04-03 08:49:49

+0

@BogdanPopa你可以試試這個:'validates_format_of:city,:with =>/^ [a-z] + $/i'? – 2015-04-03 08:54:20

相關問題