简体   繁体   中英

Best way to implement dynamic form validation Rails

I have two <select> boxes and a text input.

The first <select> is the parent and the second <select> is the child. The child gets updated by the parent via JQuery.

The values that are allowed in the text input will be dependent on the value of the <select> boxes. In some cases it needs to be an INT, in other a boolean. And in some cases a <select> of associative records.

What is the best way to achieve this using Rails 4 and Activerecord Associations and Validation?

You can implement a custom validation like this in your model:

validate :custom_validation

private
def custom_validation
  case params[:select_field_1]
  when 'foo'
    record.errors.add(:select_field_2, 'must be an integer') unless select_field_2.is_a?(Integer)
  when 'bar'
    record.errors.add(:select_field_2, 'must be a boolean') unless select_field_2.is_a?(Boolean)
  when 'baz'
    record.errors.add(:select_field_2, 'must exist') unless Model.exist?(select_field_2)
  end
end

It depends on your models and views if select_field_2 is typecasted or not. You might run into the problem that select_field_2 always returns strings. In that case you will need more methods to check if the value of that attribute acts like a integer or boolean.

See: http://guides.rubyonrails.org/active_record_validations.html#custom-methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM