How to make validation where presence of model's attribute isn't necessary, but if it is present, attribute's length must be more than three characters?
validates is used for normal validations presence , length , and the like. validate is used for custom validation methods validate_name_starts_with_a , or whatever crazy method you come up with. These methods are clearly useful and help keep data clean. That test fails.
This helper validates the attributes' values by testing whether they match a given regular expression, which is specified using the :with option. Alternatively, you can require that the specified attribute does not match the regular expression by using the :without option. The default error message is "is invalid".
Rails validation defines valid states for each of your Active Record model classes. They are used to ensure that only valid details are entered into your database. Rails make it easy to add validations to your model classes and allows you to create your own validation methods as well.
The purpose of this distinction is that with save! , you are able to catch errors in your controller using the standard ruby facilities for doing so, while save enables you to do the same using standard if-clauses.
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? }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With