views:

300

answers:

3

Hello,

How do I validate a field - so that it contains at least 3 alphabetic characters.

Valid:
Something, Foobar 111. 

Invalid:
.......

Best regards. Asbjørn Morell

+1  A: 

You can write a validate method for that.

e.g.

in your model

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

More on Rails validations here: http://api.rubyonrails.org/classes/ActiveRecord/Validations.html

DanSingerman
+5  A: 

While i prefer DanSingerman's solution, you can also go pure regex based:

   validates_format_of :password, :with => /([^a-zA-Z]*([a-zA-Z]+)[^a-zA-Z]*){3,}/
Michel de Graaf
+3  A: 

More railsy way is to validate in the model automatically

validate :yourvalue_must_contain_at_least_3_alphabetic_characters

protected 

def yourvalue_must_contain_at_least_3_alphabetic_characters 
  unless yourvalue.gsub(/[^A-Z]/i,"").size > 2
    errors.add(:yourvalue, 'should have at least 3 alphabetic characters')
  end
end
David Burrows