0

I am validating phone number with codeigniter

In my city, I apply the rule like this:

$this->form_validation->set_rules('voter_phone', 'Phone number', 'required|exact_length[8]|integer');

however, since my city doesn't have the 1 or 4 for the first character , I would like to know are there any way to add checking for this rule? Thanks for helping

Reference: http://cimple.org/user_guide/libraries/validation.html

user782104
  • 13,233
  • 55
  • 172
  • 312

2 Answers2

1

You need a callback to validate your custom validation.

//here checkphone is custom callback
$this->form_validation->set_rules('voter_phone', 'Phone number', 'required|exact_length[8]|integer|callback_checkphone');

so make a function/method called checkphone in your controller and validate your input(voter_phone)

function checkphone($num)
    {
        //your first charcter in voter_phone
        $first_ch = substr($num,0,1);
        if ($first_ch==1 || $first==4)
        {
            //set your error message here
           $this->form_validation->set_message('checkphone','Invalid Phone number,Not allowed 1 or 4 as first charcter');
            return FALSE;
        }
        else
            return TRUE;
    }
Mayank Tailor
  • 344
  • 3
  • 9
  • 1
    -1...your callback is **checkphone** and you are setting message as `set_message('voter_phone',...` you should check http://cimple.org/user_guide/libraries/validation.html – Karan Thakkar Jul 03 '14 at 05:13
1

you can use callback for that purpose its available in the same LINK you have mentioned

$this->form_validation->set_rules('voter_phone', 'Phone number', 'required|exact_length[8]|integer|callback_valid_number');

and callback function can be

public function valid_number($str)
{   
    if(!preg_match("/^[235-9]{1}[0-9]{7}$/", $str))
    {
        $this->form_validation->set_message('valid_number', 'Invalid Mobile No.');
        return false;
    }   
    else
    { 
        return true;
    }
}

this regex checks if

 1. it is required
 2. phone number is int only
 3. it should be exactly 8 digit
 4. it does not start with either 1 or 4

so you can remove required|exact_length[8]|integer

Karan Thakkar
  • 1,492
  • 2
  • 17
  • 24
  • nice regex to include all validation. Adding to this, form validation library have built in function for regex check called regex_match. But its not documented. you can see this here http://ellislab.com/forums/viewthread/195050/ – Mayank Tailor Jul 03 '14 at 06:37
  • yeah its there, but there is a bug with `regex + form validation piping` so i usually use callbacks. see http://stackoverflow.com/questions/21439805/codeigniters-regex-match for more info. @MayankTailor – Karan Thakkar Jul 03 '14 at 07:07