Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate attribute's length if present

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?

like image 296
Alek Avatar asked Apr 26 '15 15:04

Alek


People also ask

What is the difference between validate and validates in rails?

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.

How do I validate in Ruby on Rails?

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".

How does validation work in Rails?

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.

What happens on Save rails?

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.


1 Answers

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? }
like image 62
potashin Avatar answered Sep 18 '22 14:09

potashin