# Validation for one or another field

**URL:** <https://discuss.rubyonrails.org/t/validation-for-one-or-another-field/57941>\
**Category:** rubyonrails-talk\
**Created:** [March 16, 2011, 7:51pm UTC](https://discuss.rubyonrails.org/t/validation-for-one-or-another-field/57941 "2011-03-16T19:51:07Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Rodrigo\_Alves\_Vieira](https://avatars.discourse-cdn.com/v4/letter/r/13edae/32.png) [@Rodrigo\_Alves\_Vieira](https://discuss.rubyonrails.org/u/Rodrigo_Alves_Vieira)\
**Post date:** [March 16, 2011, 7:51pm UTC](https://discuss.rubyonrails.org/t/validation-for-one-or-another-field/57941/1 "2011-03-16T19:51:07Z")

</div>

Hello everyone, in my model I have amongst other fields, the :variant\_id and :cart\_id, I want to validate their presences but in my app the user only needs to set one of them, so I can’t make it validates\_presence\_of :variant\_id, :cart\_id.

I am sure there’s a solution for that, please tell me if you know!

Thanks!

---

<div class="post-metadata">

**Author:** ![Philip\_Hallstrom](https://avatars.discourse-cdn.com/v4/letter/p/bbe5ce/32.png) [@Philip\_Hallstrom](https://discuss.rubyonrails.org/u/Philip_Hallstrom)\
**Post date:** [March 16, 2011, 9:13pm UTC](https://discuss.rubyonrails.org/t/validation-for-one-or-another-field/57941/2 "2011-03-16T21:13:08Z")

</div>

> Hello everyone, in my model I have amongst other fields, the :variant\_id and :cart\_id, I want to validate their presences but in my app the user only needs to set one of them, so I can't make it validates\_presence\_of :variant\_id, :cart\_id.
> 
> I am sure there's a solution for that, please tell me if you know!

You can either write a custom validation method that returns false if both are unset or you could add some :if =\> {...} code to your validation line so it only validates one field if the other is blank. You'd need that on both validation lines and your error message would be a little confusing suggesting the user needs to pick both.

If it was me, I'd go custom so I could put up a reasonable error message.
