Rails ships with nice collection of model validations.
By default rails facilitizes our application with validations like presence, uniquiness, format etc etc.
In most applications default supplied validations are enough to serve our purpose. But in few cases we are required to add few custom validations to our rails applications.
Problem statement :
Let’s assume, we have a Coupon model for which we want to validate the format of each coupon code. let’s say our requirement is something like this :
coupon code must :
– consists of 3 uppercase ASCII letters followed by a dash , followed by an 5 digit numeric code.
Solution:
Add validation on coupon_code attribute : coupon_app/app/models/coupon.rb class Coupon < ActiveRecord::Base validates :coupon_code, :vcoupon => true end
Now let’s create a validator for coupon now. we need to define a validator that matches the expected naming convenation for :vcoupon.
VcouponValidator will be our validator which will be placed inside models / Vcoupon_validator.rb file : class VcouponValidator < ActiveModel::EachValidator def validate_each(record, attribute, value) record.errors[attribute] "59858-ABC") $ mycoupon.valid? =>false $ mycoupon.errors.full_messages.to_sentence => coupon_code is an invalid coupon code. $ mycoupon.coupon_code = "ABC-59858" $ mycoupon.valid? =>true
-> hence we have created our own custom validator to check a coupon code is valid or invalid.
->Our validation code separated from the rest of the model making it easier to understand & maintain.