views:

165

answers:

2

I want to validate landphone and mobile phone fields in my CI application. I have set validation rules as integer but user cannot enter values seperated by " - " . If i use "text" type, user can enter alphabets also.....how do i solve this issue....i want user to enter "-" and "+" values in the fields and not any other texts

Code:

$this->form_validation->set_rules('land_phone','Land Phone','trim|required|integer|min_length[1]|max_length[50]|xss_clean');
$this->form_validation->set_rules('mobile_phone','Mobile Phone','trim|required|integer|min_length[1]|max_length[50]|xss_clean');
A: 

Out of the box, I don't think there is anything that can do exactly that. You'll probably need to use a callback function and check it with some regex. I'm not too fluent with regex so I couldn't tell you exactly what you need there.

You can find more about callbacks in the CodeIgniter User Guide: http://codeigniter.com/user_guide/libraries/validation.html

Chris Schmitz
+2  A: 

You cannot enter a number with "-" since you defined integer as the validation rule. Therefore, the validation will fail. You need to work with RegEx so that you can create more complex validation. See the topic on validations in the CI manual for more info.

Your validation rule:

$this->form_validation->set_rules('foo', 'Number', 'callback_number_validation');

Note how the keyword callback_ is used to identify CI your function for validation.

Your callback function:

//$str will be the value you want to verify
function number_validation($str) {
    return preg_match("your_regex", $str) ? true: false;
}
DrColossos