Jason Crump
Jason Crump

Reputation: 445

rails strip non numeric values before save

I have searched and it looks like this should be simple but I can't get it to work. I am trying to remove all non-numeric characters prior to saving a phone number. This is what I have currently:

before_save { |workorder| workorder.phonenumber = 
                  phonenumber.to_s.gsub(/\D/, '').to_i }

So if a user inputs

925-555-5555

It should save 9255555555 but it is actually saving only 925 and ignoring everything after

I also tried:

before_save { |workorder| workorder.phonenumber = 
                  phonenumber.to_s.gsub(/[^0-9]/, "").to_i }

with the same result.

Solved:

def raw_phonenumber
  self.phonenumber
end
def raw_phonenumber=(s)
  self.phonenumber=s.gsub(/\D/, '')
end

Upvotes: 29

Views: 20699

Answers (3)

justapilgrim
justapilgrim

Reputation: 6882

The easiest way to do it is by mutating the field= method:

def field=(value)
  super(value.delete('^0-9'))
end

Upvotes: 5

Baldrick
Baldrick

Reputation: 24340

You certainly have defined the phonenumber column as number. That's why when you set '925-555-5555' in the phonenumber attribute, it is casted to a number, and only 925 is kept.

The best solution is to change the type of the column in your database to string. Create a new migration:

change_column :table_name, :phonenumber, :string, limit: 30

Otherwise, you can override the setter like this to remove the non numeric characters (but it won't fix phone numbers starting with '0's):

def phonenumber=(phonenumber)
  write_attribute(:phonenumber, phonenumber.gsub(/\D/, ''))
end

More alternatives in this blog post

Upvotes: 62

Ankit Varshney
Ankit Varshney

Reputation: 101

You can create custom method for save/display mobile number like this:

def mobile_number(arg)

if arg.downcase.include?('special chars')

phone_number = arg.downcase.split('special chars')

phone = if phone_number[0].to_i == 0 || phone_number[0].to_i.to_s.size < 10
number_to_phone(phone_number[0].gsub!(/[^0-9A-Za-z]/, '').to_i, area_code: true)
else
number_to_phone(phone_number[0].to_i, area_code: true)
end

return phone.to_s + ' Ext'+ remove_unnecessary_keywords(phone_number[1])

elsif arg.include?('(') || arg.include?(')') || arg.include?('-') || 
arg.include?('.') || arg.include?(' ')

return  number_to_phone(arg.gsub!(/[^0-9A-Za-z]/, '').to_i, area_code: true)    

else

return number_to_phone(arg.to_i, area_code: true) 

end

end  

Upvotes: 0

Related Questions