简体   繁体   中英

How to validate a field only if an option is selected - RAILS 5

could one kindly advise me how i validate a field only if an option is selected

  • so i have the selector that has the options: parent & service provider
  • when service provider is selected the hidden selector services is displayed
  • i want to validate the presences of services only when service provider is selected (not when parent is selected) as per image

will it be written something like the below: validates_presence_of :category_service_id, presence: true, if: :category_segment_id?, message: "can't be blank "

could one kindly advise me on this 在此处输入图片说明

You're very close. What you need to do is make a conditional validation (More about it in the official guides ).

You'd need to do the following:

validates_presence_of :category_service_id, if: :service_provider?

# Marking the validation check method as private is optional, but recommended
private

def service_provider?
  <Your code to check if segment is service_provider comes here>
end

message is not required since the default error message would be can't be blank .

I would highly recommend reading the doc mentioned in the link above for a better understanding of validations.

NOTE: service_provider? method is not required in case you're using enums to decide between service_provider and parent since enums define option? methods by default.

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