# Form Validation

**URL:** <https://www.ruby-forum.com/t/form-validation/84790>\
**Category:** Rails\
**Created:** [March 21, 2006, 6:11pm UTC](https://www.ruby-forum.com/t/form-validation/84790 "2006-03-21T18:11:37Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![pete](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3ab097/32.png) [@pete](https://www.ruby-forum.com/u/pete)\
**Post date:** [March 21, 2006, 6:11pm UTC](https://www.ruby-forum.com/t/form-validation/84790/1 "2006-03-21T18:11:37Z")

</div>

Hi,

I’ve got an interesting one here 🙂

I have a form with three fields :

serial\_number  
initial  
surname

now, if serial\_number is entered, it must be between 1 and 64000. If  
it’s filled in, the other two fields must be blank. If serial\_number is  
left blank then the other two boxes must be filled.

Any suggestions?

---

<div class="post-metadata">

**Author:** ![pete](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/p/3ab097/32.png) [@pete](https://www.ruby-forum.com/u/pete)\
**Post date:** [March 21, 2006, 7:31pm UTC](https://www.ruby-forum.com/t/form-validation/84790/2 "2006-03-21T19:31:10Z")

</div>

do a custom validation in your model

def validate  
if serial\_number.nil?  
errors.add(‘field1’, “Sorry field1 cant be blank when using a  
serial  
number”) if field1.nil?  
errors.add(‘field2’, “Sorry field2 cant be blank when using a  
serial  
number”) if field2.nil?  
else  
errors.add(‘serial\_number’,“Sorry serial number must be between 1  
and  
64000”) if serial\_number \< 1 || serial\_number \> 64000  
errors.add(‘field1’, “Sorry field1 must be blank when using a  
serial  
number”) if ! field1.nil?  
errors.add(‘field2’, “Sorry field2 must be blank when using a  
serial  
number”) if ! field2.nil?  
end  
end

```
 quick and dirty but should come close :-) Sometimes you have to 

```

use  
field.nan? instead of nil? if the value is a number, at least in my  
experiences. Not sure why types of data is in your fields.

adam
