user782104
user782104

Reputation: 13555

How to validate post value : the first character not allow 1 or 4 in codeigniter?

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

Upvotes: 0

Views: 898

Answers (2)

Mayank Tailor
Mayank Tailor

Reputation: 344

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;
    }

Upvotes: 1

Karan Thakkar
Karan Thakkar

Reputation: 1467

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

Upvotes: 1

Related Questions