Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails validate specific value

I have this code

I have these options and if the user select anything except 'British Columbia' to give him error message that the province have to 'British Columbia'

I believe it will solve by using the model validation

<%= f.label :province ,"Province (required)"%><br>
    <%= f.select(:province, [["Select One", ""],'Alberta','British Columbia','Manitoba','New Brunswick','Newfoundland and Labrador','Nova Scotia','Northwest Territories','Nunavut','Ontario','Prince Edward Island','Quebec','Saskatchewan','Yukon'], {}) %>

User.rb

  validates :province, presence: "British Columbia"
like image 596
nourza Avatar asked Oct 14 '16 22:10

nourza


1 Answers

You shouldn't use presence, it's the wrong validation. You should use inclusion:

validates :province, inclusion: { in: %w[British Columbia] }

You realize this is a nonsensical problem, right? What's the point of offering several alternatives in the view if the validation will only accept one?

like image 65
John Feltz Avatar answered Oct 23 '22 10:10

John Feltz