如何驗證字段 - 以便它包含至少3個字母字符。Rails,validates_format_of - 最少4個字母字符
Valid:
Something, Foobar 111.
Invalid:
.......
此致敬意。 AsbjørnMorell
如何驗證字段 - 以便它包含至少3個字母字符。Rails,validates_format_of - 最少4個字母字符
Valid:
Something, Foobar 111.
Invalid:
.......
此致敬意。 AsbjørnMorell
更多railsy方式是在模型中自動驗證
validate :yourvalue_must_contain_at_least_3_alphabetic_characters
protected
def yourvalue_must_contain_at_least_3_alphabetic_characters
errors.add(:yourvalue, 'should have at least 3 alphabetic characters') if yourvalue.gsub(/[^A-Z]/i,"").size > 2
end
您可以爲此編寫一個validate
方法。
例如
在模型protected
def validate
unless your_field.gsub(/[^A-Z]/i,"").size > 2
errors.add("your_field", "Must contain at least 3 alphabetical characters")
end
end
更多on Rails的驗證此:http://api.rubyonrails.org/classes/ActiveRecord/Validations.html
雖然我更喜歡DanSingerman的解決方案,你也可以去純粹的正則表達式基礎:
validates_format_of :password, :with => /([^a-zA-Z]*([a-zA-Z]+)[^a-zA-Z]*){3,}/