Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Validate Field is True, If Present

I've found plenty of posts around how to validate a field is present, if another condition is true, such as these:

Rails: How to validate format only if value is present?

Rails - Validation :if one condition is true

However, how do I do it the opposite way around?

My User has an attribute called terms_of_service.

How do I best write a validation that checks that the terms_of_service == true, if present?

like image 681
yellowreign Avatar asked Nov 21 '25 05:11

yellowreign


1 Answers

You're looking for the acceptance validation.

You can either use it like this:

class Person < ApplicationRecord
  validates :terms_of_service, acceptance: true
end

or with further options, like this:

class Person < ApplicationRecord
  validates :terms_of_service, acceptance: { message: 'must be abided' }
end

[edit]

You can set the options you expect the field to be as well, as a single item or an array. So if you store the field inside a hidden attribute, you can check that it is still "accepted" however you describe accepted:

class Person < ApplicationRecord
  validates :terms_of_service, acceptance: { accept: ['yes', 'TRUE'] }
end
like image 130
philnash Avatar answered Nov 22 '25 18:11

philnash



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!