Reputation: 1313
I need a to set up a validation for student ID's and the CI native library is not cutting it, so I extended. I however am having an issue getting it work, and I don't quite know where I am goofing up. This is my first crack at REGEX so go easy on me. Here is my Code :
<?php
if(!defined('BASEPATH')) exit('No direct script access allowed');
class MY_Form_validation extends CI_Form_validation
{
public function is_valid_student_id($str)
{
if(strlen($str) > 9)
{
$this -> set_message('is_valid_student_id', 'A-Number can not be over 9 characters');
return FALSE;
}
elseif(strlen($str) < 9)
{
$this -> set_message('is_valid_student_id', 'A-Number can not be under 9 characters');
return FALSE;
}
elseif((($str[0]) !== 'a') && (($str[0]) !== 'A'))
{
$this -> set_message('is_valid_student_id', 'A-Number must begin with the letter "A"');
return FALSE;
}
elseif(ctype_alpha($str[0]))
{
if(is_numeric(substr($str, 1, strlen($str) - 1)))
{
return TRUE;
}
else
{
$this -> set_message('is_valid_student_id', 'A-Number must have 8 digits 0 - 9');
return FALSE;
}
}
else
{
$this -> set_message('is_valid_student_id', 'A-Number must begin with the letter "A"');
return FALSE;
}
}
}
Then to use the validation I do this :
if (!$this->input->post('student') == 'yes') {
$this->form_validation->set_rules('anum', 'A Number', 'required|is_valid_student_id|exact_length[9]');
}
I've been following these good /// tutorials, but I am still a little confused. Any help would be great. Thank you
Upvotes: 0
Views: 94
Reputation: 616
I think no need to extend the library just make one callback method in your controller and add above code in it...Just Make one method called is_anum and put your code In it
if (!$this->input->post('student') == 'yes') {
$this->form_validation->set_rules('anum', 'A Number', 'required|callback_is_anum|exact_length[9]');
}
function is_anum($str)
{
if (((substr($str, 0) !== 'a') || substr($str, 0) !== 'A') && (!preg_match("/[^0-9]/", $str) )) // If the first character is not (a or A) and does not contain numbers 0 - 9
{ // Set a message and return FALSE so the run() fails
$this->set_message('is_anum', 'Please enter a valid A-Number');
return FALSE;
} else
{
return TRUE;
}
}
Upvotes: 0
Reputation: 82028
If you're using the callback_
syntax, then the function called needs to be on the controller. If you're adding it to the Form_Validation
library directly, though, you don't need callback_
. Try this:
$this->form_validation->set_rules(
'anum', 'A Number', 'required|is_anum|exact_length[9]');
Upvotes: 2