ricardo
ricardo

Reputation: 215

International Phone number Validation with whitespace

I am using codeigniter validation library...for a international number i am trying to accept a Numeric 15 digits..also white space shud be allowed.. but below does not work for some reason...it does not accept whitespace...

          if(isset($data['perfume_int_contact']))
           {
            //$this->form_validation->set_rules('phone_int_area_code','Contact Phone Number','trim|required|numeric');

            $this->form_validation->set_rules('phone_int_first','Contact Phone Number','trim|required|numeric');                        

i shud be able to enter like : 1234 1234 1234 45678 Should i make my own validation class just for this ? or can i make a callback function using it in the set_rules..? Or make a my own regex? Any inputs appreciated

Upvotes: 0

Views: 1326

Answers (2)

Madan Sapkota
Madan Sapkota

Reputation: 26101

if (isset($data['perfume_int_contact'])) {
    $this->form_validation->set_rules('phone_int_first', 'Contact Phone Number', 'trim|numeric|required|callback_phone_check');
}

function phone_check($phone_number)
{
    $regex = '/^\d{3}\s\d{3}\s\d{4}\s\d{3}$/'; // validates 123 123 1234 123
    if (!preg_match($regex, $phone_number)) {
        $this->form_validation->set_message('phone_check', 'Phone Number not valid.');
        return false;
    }
    return true;
}

Upvotes: 1

Dino Babu
Dino Babu

Reputation: 5809

// in form validation rules

$this->form_validation->set_rules('phone_int_first', 'Contact Phone Number', 'trim|required|max_length[15]|callback_checkPhone');

// callback function

  function checkPhone($phoneNumber) {
    $output = preg_match('/[^0-9\s]/', $phoneNumber);
    if (empty($output)) {
      return TRUE;
    } else {
      $this->form_validation->set_message('checkPhone', 'This phone number conatins only numbers & white space');
      return FALSE;
    }
  }

Upvotes: 1

Related Questions