Rails: Validating min and max length of a string but allowing it to be blank
I think it might need something like:
validates_length_of :foo, minimum: 5, maximum: 5, allow_blank: true
More examples: ActiveRecord::Validations::ClassMethods
How to validate text isn't blank in Rails
Rails adds the handy method blank?
which checks for false, nil and empty strings as described here.
Rails also adds the handy validator allow_blank: false
.
So in your case it should be:
validates :body, presence: true, allow_blank: false
Edit (original answer above):
As stated in the answer below, allow_blank: false
is not needed as that's the default behaviour of presence: true
.
Validate attribute's length if present
You can allow attribute to be blank with allow_blank: true
or nil
with allow_nil: true
and also check the length:
:
validates :attr, length: { minimum: 4 }, allow_blank: true
validates :attr, length: { minimum: 4 }, allow_nil: true
You can also use if:
or unless:
:
validates :attr, length: {minimum: 4}, unless: -> (item) { item.blank? }
Rails - REGEX - validating length of non whitespace / special characters
if you would have aux column like 'filtered_title' you could do:
before_save :filter_title
def filter_title
self.filtered_title = title.gsub(/[^0-9a-zA-Z]/, '') // strip unneeded chars
end
and your validator, but on a the new column
validates :filtered_title,
presence: true,
length: { minimum: 4, maximum: 140 },
format: { with: /([A-z0-9])/ }
how to validate mobile and also allow blank field in mobile in ruby
Change allow_nil
to allow_blank
. Chances are, you are submitting empty string ''
, instead of nil
(json null
) value. So, to allow it, you need to specify :allow_blank => true
Validating min and max length of a phone number according to select of country code
You can't do that; if
would evaluate at class definition, not at validation time. You either need to use :if
option:
validates_length_of :phone, :minimum => 10, :maximum => 10,
:if => Proc.new { |x| x.country_code == 91 }
or you need to use a custom validator, something like:
PHONE_LENGTH_LIMITS_BY_COUNTRY_CODE = {
91 => [10, 10]
}
def phone_number_is_correct_according_to_country_code
min, max = *PHONE_LENGTH_LIMITS_BY_COUNTRY_CODE[country_code]
if phone.length < min || phone.length > max
errors.add(:phone, "must be between #{min} and #{max} characters")
end
end
validate :phone_number_is_correct_according_to_country_code
(Disclaimer: untested code)
Validate a URL if present, but allow it to be blank
Use the allow_blank option
http://guides.rubyonrails.org/active_record_validations.html#allow-blank
Or an unless with proc
http://guides.rubyonrails.org/active_record_validations.html#using-a-proc-with-if-and-unless
Validating datetime entries in a model
Your validation is still invoked when starts_at
is blank/nil, even though you've defined a presence
validation: there's no hierarchy to the validations, so one failing can't cause others to be skipped.
Consequently, your validation method should just skip the check if either value is blank -- leaving the presence
validation to record the error.
def end_time_is_valid
return if starts_at.blank? || ends_at.blank?
error_msg = 'Trip cannot ends before it began'
errors.add(:ends_at, error_msg) if ends_at < starts_at
end
Related Topics
Ruby Strftime: Month Without Leading Zero
Uninstall Ruby Version from Rbenv
Neither Ruby and Nor Irb Can Load .Rb File in Current Directory
How to Use Define_Method Inside Initialize()
How to Call Applicationcontroller Methods from Applicationhelper
Why Are Constants from Extended Module Not Available in Class Methods Declared with Self
How to Validate the Date Such That It Is After Today in Rails
How to Reference an Embedded Document in Mongoid
How to Check If a Folder Exists in Chef
How to Check If a Variable Is an Instance of a Class
How to Use Capybara in Pure Ruby (Without Rails)
Ruby: Get All Keys in a Hash (Including Sub Keys)
Code to Generate Gaussian (Normally Distributed) Random Numbers in Ruby