Phone Number Validator/Filter using jQuery or Zend Form?
-
21-09-2019 - |
Question
I'm thinking about adding some validation/filtering to the phone number field of my Zend Framework application. Not sure if this is something I should do or not.
I thought it might be helpful for users to have such a feature so I could enforce a particular display format. I'm not sure if the formatting of the phone number should be stored in the database, or when it is retrieved from the database. I don't want to be too strict about this because it's not really that important. I just wanted to prevent half the people from entering 123.456.7890
as their phone number format and the other half entering (123) 456-7890
as the other format. I want the listing of phone numbers to look consistent. So maybe I should use some javascript to help the user enter their number? Maybe there is a jQuery plugin that already does that and I can integrate it with my Zend Form?
What do you think?
Solution
OTHER TIPS
You will still want to enforce validation on the back end as javascript validation can be bypassed easily. This is my validation plugin which forces +1.1234567890:
class App_Validate_Phone extends Zend_Validate_Abstract
{
const NOT_VALID = 'phoneInvalid';
protected $_messageTemplates = array(
self::NOT_VALID => "Phone number '%value%' must be in the format +COUNTRYCODE.PHONENUMBER. Example: +1.4071234567"
);
public function isValid($value)
{
$this->_setValue($value);
if (!preg_match('/^\+([0-9]+)\.([0-9]+)$/',$value)) {
$this->_error(self::NOT_VALID);
return false;
}
return true;
}
}
If you google phone validation regex you can find any number of validation regular expressions which you can substitute in preg_match() for your particular needs.
You dont need to create a custom validator to phones. Zend has a proposal for a phone validator using localization. Whilst not ready yet, you can use the Regex validator:
//Add element for phoneNumber1
$this->addElement('text', 'phoneNumber1', array(
'label' => 'Primary Phone Number',
'required' => false,
));
$phone1 = $this->getElement('phoneNumber1');
$phone1->addValidator('regex', false, array('pattern' => '^[2-9][0-9]{2}-[0-9]{3}-[0-9{4}$', 'messages' => 'Enter a valid Phone Number'));