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
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
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
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,}/
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