'Ruby on Rails | How to apply validation on rails form

I am adding the promo code option for my application. I want to apply validation on the form that will match the entered promo code by the user to the promo code that has been already there in the admin dashboard (Activeadmin is used for admin dashboard).

I have tried a few options but nothing works. Examples that I have tried -

def validate_promo_code
  if promo_code.present? and (!promo_code.match(EngineName::PromoCode.promo_code))
    errors.add :promo_code, "must be a valid promo code"
  end
end
def validate_promo_code
 if promo_code.present? and (promo_code != EngineName::PromoCode.where(promo_code: promo_code))
   errors.add :promo_code, "must be valid promo code"
   return;
 end
end

Does anyone has any idea how to achieve this? Please Help!



Solution 1:[1]

You have to make your activerecord model aware of the validation using the validate dsl statement. Does this work?

validate :ensure_valid_promo_code

def ensure_valid_promo_code
  if promo_code.present? && (!promo_code.match(EngineName::PromoCode.promo_code))
    errors.add :promo_code, "must be a valid promo code"
  end
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sjors Branderhorst