Santosh Aryal
Santosh Aryal

Reputation: 1376

Rails Validation on update only if form field has value

How to validate rails app on update only if the submitted form field has value?

It should not validate if the submitted form field is blank.

User.rb

validates_presence_of :search_card, on: :update

def search_card
    card = Card.find_by_barcode(self.barcode)
    if card.nil?
      errors.add(:invalid_card, ", Please provide another card")
    end
  end

Upvotes: 1

Views: 1941

Answers (2)

pan.goth
pan.goth

Reputation: 1485

Update

You should fire search_card method on before_validation callback, if barcode has been changed:

before_validation :search_card, on: :update, if: Proc.new { |u| u.barcode_changed? }

Old answer (wrong)

You should use if statement with Proc. Try this:

validates_presence_of :search_card, on: :update, if: Proc.new { |u| u.search_card.present? }

Upvotes: 1

Chakreshwar Sharma
Chakreshwar Sharma

Reputation: 2610

You can use client side validations for it. For more details see https://github.com/DavyJonesLocker/client_side_validations. Also, use callback(before_create) to validate the values.

Upvotes: 0

Related Questions