# Set attribute value from custom validation

**URL:** <https://www.ruby-forum.com/t/set-attribute-value-from-custom-validation/92902>\
**Category:** Rails\
**Created:** [April 25, 2007, 3:26pm UTC](https://www.ruby-forum.com/t/set-attribute-value-from-custom-validation/92902 "2007-04-25T15:26:59Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![tony](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/t/ee7513/32.png) [@tony](https://www.ruby-forum.com/u/tony)\
**Post date:** [April 25, 2007, 3:26pm UTC](https://www.ruby-forum.com/t/set-attribute-value-from-custom-validation/92902/1 "2007-04-25T15:26:59Z")

</div>

Is there any way to set a value from a custom validates?

There are times when a user has submitted the appropriate information,  
but just not in the exact form I am looking for and I would like to  
override what they entered without generating a warning.

For example, I validating phone numbers and have defined  
“validates\_us\_phone”. As long as the entry has 10 or 11 digits before  
an optional ‘x’ (for extension), I’d like to accept the entry, but  
modify it before saving it.

This way, people can enter:

1234567890  
(123)456-7890  
1 123 456-7890  
123-456-7890 x123

and the validates would change their entries to

11234567890  
11234567890  
11234567890  
11234567890x123

The validates\_us\_phone function is written and works up to the point  
where the new value overrides the supplied value.

Given the following code near the top of validates\_us\_phone:

validates\_each attr\_names do |m, a, v|

are there any methods available that would let me set the value of the  
attribute?

I am guessing that the alternative would be to break this into two  
parts:

- Validate the entry, but don’t change the value
- Add a function in before\_save that would assume the entry is valid  
and would massage it into the correct format

Thanks,

- Tony
