# Validates

**URL:** <https://www.ruby-forum.com/t/validates/161205>\
**Category:** Rails\
**Created:** [February 24, 2009, 9:56am UTC](https://www.ruby-forum.com/t/validates/161205 "2009-02-24T09:56:20Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [February 24, 2009, 9:56am UTC](https://www.ruby-forum.com/t/validates/161205/1 "2009-02-24T09:56:20Z")

</div>

If I have a table: users(id, name, address, city)

How can I validate:  
Name must be entered, but address and city can be null, but if there is  
address, there also must be a city. So city can’t be null, if address is  
not, but bouth address and city can be null.

validates\_presence\_of name  
validates ???

---

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [February 24, 2009, 10:11am UTC](https://www.ruby-forum.com/t/validates/161205/2 "2009-02-24T10:11:11Z")

</div>

Jo Jo wrote:

> If I have a table: users(id, name, address, city)
> 
> How can I validate:  
> Name must be entered, but address and city can be null, but if there is  
> address, there also must be a city. So city can’t be null, if address is  
> not, but bouth address and city can be null.
> 
> validates\_presence\_of name  
> validates ???

Hi,  
Try with following code.

def validate  
errors.add(:city,“City should not be empty”) if city==nil and  
address!=nil  
end

---

<div class="post-metadata">

**Author:** ![giga](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/b9bd4f/32.png) [@giga](https://www.ruby-forum.com/u/giga)\
**Post date:** [February 24, 2009, 5:56pm UTC](https://www.ruby-forum.com/t/validates/161205/3 "2009-02-24T17:56:10Z")

</div>

class User  
validates\_presence\_of :name  
validates\_presence\_of :city, :if =\> :address  
validates\_presence\_of :address, :if =\> :city  
end

- 

Maurício Linhares  
[http://alinhavado.wordpress.com/](http://alinhavado.wordpress.com/) (pt-br) | [http://blog.codevader.com/](http://blog.codevader.com/)  
(en)
