Validating only attributes that are present in a form I want to skip validations based on attributes. If certain attributes are not in form so I do not want to validate them.

Currently, if I post them from one form which has 1 field, it still validates other 9 fields and show me errors that it cant be blank.

If I check from big form which has 10 fields, it passes successfully.

The below code did trick for me but my main intention is to refactor so it will fullfil its purpose as i stated above.

Code is:

validates :teacher_number, presence: true, if: "teacher_number &amp;&amp; teacher_number.blank?"
  validates :title, presence: true, if: "title &amp;&amp; title.blank?"
  validates :name, presence: true, if: "name &amp;&amp; name.blank?"
  validates :gender, presence: true, if: "gender &amp;&amp; gender.blank?"
  validates :location, presence: true, if: "location &amp;&amp; location.blank?"
  validates :dob, presence: true, if: "dob &amp;&amp; dob.blank?"
  validates :contact_mobile, presence: true, if: "contact_mobile &amp;&amp; contact_mobile.blank?"
  validates :contact_home, presence: true, if: "contact_home &amp;&amp; contact_home.blank?"
  validates :street, presence: true, if: "street &amp;&amp; street.blank?"
  validates :city, presence: true, if: "city &amp;&amp; city.blank?"
  validates :state, presence: true, if: "state &amp;&amp; state.blank?"
  validates :zip_code, presence: true, if: "zip_code &amp;&amp; zip_code.blank?"
  validates :country, presence: true, if: "country &amp;&amp; country.blank?"
  validates :teacher_number, uniqueness: {scope: :school_id}, if: "teacher_number &amp;&amp; teacher_number.blank?"
  validate  :teacher_number_existance, :on =&gt; :create, if: "self.teacher_number &amp;&amp; self.teacher_number.blank?"
  validate  :school_existance, :on =&gt; :create, if: "self.teacher_number &amp;&amp; self.teacher_number.blank?"


I simply wants to do something like:


before_validation :skip_validations

def strip_validations
    [:teacher_number, :title, :name, :gender, :location, :dob, :contact_mobile, :contact_home, :street, :city, :state, :zip_code, :country].each do |attr|

      errors.add("Teacher", " #{attr} can't be blank") if attr &amp;&amp; attr.blank?

    end
  end



But above code does not work for my cases. Any good work around?
You just need to change the method call from skip_validation to strip_validations.

before_validation :strip_validations

    def strip_validations
      ['teacher_number', 'title', 'name', 'gender', 'location', 'dob', 'contact_mobile', 'contact_home', 'street', 'city', 'state', 'zip_code', 'country'].each do |attr|

        errors.add("Teacher", " #{attr} can't be blank") if send(attr.to_sym) &amp;&amp; send(attr.to_sym).blank?

      end
    end


for more specific error messages you can use

errors.add("Teacher", {attr =&gt; " #{attr} can't be blank"}) if send(attr.to_sym) &amp;&amp; send(attr.to_sym).blank?