Joe
Joe

Reputation: 401

how to validate user phone number in CakePhp

I have created a user registration form in CakePHP. My intention is if user provide the phone number then it should be numeric and unique. So I defined follwing rules:

 'phone_no_should_be_numeric'=>array(
                                      'rule' => 'numeric',
                   'message'=>'Phone number should be numeric'
                                ),
'Phone_no_should_be_unique'=>array(
                              'rule' => 'isUnique',
                  'message'=>'Phone number already exist'
            ),

But because of this rule it is forcing user to enter phone number. Which i don't want. My intention is if user provide the phone number then it should be unique and numeric. Can anyone suggest me what is the best way to tackle such issue.

Thnx in advance, joe

Upvotes: 0

Views: 16138

Answers (4)

FOR +71234567891

           'phone' => array(
                'rule' => array('phone', '/\+7\d{10}/', 'all'),
                'message' => '+79001234567'
            ),

Upvotes: 0

Sudhir Bastakoti
Sudhir Bastakoti

Reputation: 100175

Do 'allowEmpty' => true:

'phone_no_should_be_numeric'=>array(
'rule' => 'numeric',
'allowEmpty' => true, //validate only if not empty
'message'=>'Phone number should be numeric')

See: Validation

Upvotes: 4

Pank
Pank

Reputation: 14268

Custom Model validation for US Phone

Allowed US Format: 123-123-1234, (123) 123 1234, 123.132.1234, 1234567891

Input field name is "phone_num"

'phone_num' => array(
        'rule' => array('isValidUSPhoneFormat')
    ),


 /*isValidUSPhoneFormat() - Custom method to validate US Phone Number
 * @params Int $phone
 */
 function isValidUSPhoneFormat($phone){
 $phone_no=$phone['phone_num'];
 $errors = array();
    if(empty($phone_no)) {
        $errors [] = "Please enter Phone Number";
    }
    else if (!preg_match('/^[(]{0,1}[0-9]{3}[)]{0,1}[-\s.]{0,1}[0-9]{3}[-\s.]{0,1}[0-9]{4}$/', $phone_no)) {
        $errors [] = "Please enter valid Phone Number";
    } 

    if (!empty($errors))
    return implode("\n", $errors);

    return true;
}

Upvotes: 2

Dave
Dave

Reputation: 29121

Setting 'allowEmpty'=>true will keep it from requiring them from entering data.

Another great option is the built in "phone validation" (if you're users are US residents). This allows them to enter a phone number in many ways including (xxx) xxx-xxxx and lots more.

If your users are not US residents (or mix of different nationalities), the better solution than "numeric" would be to supply a regular expression to check the phone numbers (details here):

An example of a regex for a phone number is here (along with a lot of other common regex examples).

Overall, your users will thank you for allowing them to type their phone number(s) in any way they want instead of just lots of numbers.

Upvotes: 2

Related Questions