php - Custom Callback Validation Function to Achieve a Custom Error Message -
i have ci form field requiring decimal number. when field fails validation user gets unhelpful message. "the field must decimal". poor user experience user feels should able use leading period. e.g. ".4". trying create custom callback validation function achieve custom error message. here controller (simplified)...
<?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 required in 0.00 format.'); return false; } else { return true; } } } ?> when testing, error not thrown, ever since changed validation decimal decimal custom. missing something?
preg_match() returns true when it's valid number you're trying throw error. oposite.. (note exclamation mark before preg_match)
if ( !preg_match('/^[\-+]?[0-9]+\.[0-9]+$/', $str) ) { $this->form_validation->set_message('decimalcustom', 'the %s field required in 0.00 format.'); return false; } else { return true; }
Comments
Post a Comment