我需要设置一个学生ID的验证,CI本地库没有削减它,所以我扩展了。然而,我遇到了一个让它工作的问题,我不知道我在哪里搞砸了。这是我在REGEX的第一次破解,所以对我来说很容易。这是我的代码:
<?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;
}
}
}
然后使用验证我这样做:
if (!$this->input->post('student') == 'yes') {
$this->form_validation->set_rules('anum', 'A Number', 'required|is_valid_student_id|exact_length[9]');
}
答案 0 :(得分:2)
如果您使用callback_
语法,则调用的函数需要在控制器上。但是,如果您直接将其添加到Form_Validation
库,则不需要callback_
。试试这个:
$this->form_validation->set_rules(
'anum', 'A Number', 'required|is_anum|exact_length[9]');
答案 1 :(得分:0)
我认为不需要扩展库只需在控制器中创建一个回调方法并在其中添加上面的代码...只需创建一个名为is_anum的方法并将代码放入其中
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;
}
}
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;
}
}