实现自定义错误消息的自定义回调验证函数


Custom Callback Validation Function to Achieve a Custom Error Message

我有一个CI表单,其中一个字段需要十进制数。目前,当字段验证失败时,用户会得到一条无用的消息。"该字段必须是十进制"。对于那些认为自己应该使用前置期的用户来说,这是一种糟糕的用户体验。如。"4"。我试图创建一个自定义回调验证函数来实现自定义错误消息。这是我的控制器(简化)…

<?php
class Form extends CI_Controller {
    function index()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');        
    $this->form_validation->set_rules('expenses', 'Expenses',   'trim|max_length[50]|callback_decimalcustom|xss_clean');
        if ($this->form_validation->run() == FALSE)
        {
    $parent_data = array('country' => $countrydata, 'currency' => $currencydata, 'tour' => $tourdata, 'riders' => $ridersdata, 'measurement' => $measurementdata, 'tourdistance' => $tourdistance);
    $this->load->view('myform', $parent_data);
        }
        else        
    {                       
    $sql= array (
        'expenses'=>$this->input->post('expenses'),
            );
    $ins = $this->db->insert('donations',$sql);
    $this->load->view('formsuccess');
        }
    }   
    public function decimalcustom($str) //Custom decimal message
    {    
        if (preg_match('/^['-+]?[0-9]+'.[0-9]+$/', $str))
        {
            $this->form_validation->set_message('decimalcustom', 'The %s field is required in 0.00 format.');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
}
?>

测试时,没有抛出错误,因为我将验证从十进制更改为十进制自定义。我错过什么了吗?

preg_match()返回TRUE当它是一个有效的数字,但你试图抛出一个错误。做相反的事……(注意preg_match前的感叹号)

if ( !preg_match('/^['-+]?[0-9]+'.[0-9]+$/', $str) ) {
   $this->form_validation->set_message('decimalcustom', 'The %s field is required in 0.00 format.');
   return FALSE;
}
else {
   return TRUE;
}