我需要为学生 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]');
}