Magento – Format Phone number before it’s saved to the database

customer

I am looking for a way to make sure when a phone number is added to the database for an order/customer that it is stripped of all non-numeric characters.

I have code to strip the characters and ensure it is all digits/numbers however I am not sure how I can make it hook in and do this right before saving to the database to make sure it gets saved as just numbers.

Any ideas on the best way to do this and how?

$str = '(760) 451-2832';
$phone = preg_replace("/[^a-zA-Z0-9]/", "", $str);

Best Answer

If you do not care about validation and displaying an error to the user you can simply listen to the event customer_address_save_before this will give you the address object and allow you to make changes to it before the save is performed.

You can then make a function similar to below and this will change the telephone attribute.

public function customerAddressSaveBefore(Varien_Event_Observer $observer) {
    $customer_address = $observer->getCustomerAddress();
    $telephone = $customer_address->getTelephone();
    $customer_address->setTelephone(preg_replace("/[^a-zA-Z0-9]/", "", $telephone));
}
Related Topic