Hi Guys,
In my previous blog Format validators in rails, I talked about validations in rails and now I am here again with one of the most commonly used helper available in rails, that is length.
Length validator is used to validate the length of the attribute value. One of the most common use case is that mobile number must be of only 10 digits. Rails provides so many options for specifying length constraints as:
- :minimum- The attribute value length must be more than the specified length.
- :maximum- The attribute value length must be lesser than the specified length.
- :in (or :within)- It specifies a range of length and the attribute value length must be within that.
- :is- The attribute value length must be same as the given length
We can also change the default error messages provided by rails that depends on validation type. For customizing error message we can use
:too_long,
:too_short,
:wrong_length and
%{count}.
Thus as now we are aware about most of the things related to length validator, lets have an example of a simple registration form that contains all the length constraints with customized messages:
class Blogger < ActiveRecord::Base
validates :blogger_name, length: { minimum: 2,
too_short: "Name must be greater than or equal to %{count} characters }
validates :about, length: { maximum: 100,
too_long: "Characters cannot be more than %{count}" }
validates :password, length: { in: 8..20 }
validates :phone_number, length: { is: 10, }
end
One more helper available to calculate the attribute value length according to our requirement is
:tokenizer. Suppose if we want that about of the blogger can have maximum 20 words then we can specify as:
class Blogger < ActiveRecord::Base
validates :about, length: {
maximum: 20,
tokenizer: lambda { |str| str.split(/\s+/) },
too_long: "about can be of maximum %{count} words"
}
end
Hope you liked this blog. See below for more Rails validation helpers
0 Comment(s)