2017-08-12 74 views
0

是否可以使用codeigniter驗證類驗證數字和小數值?codeigniter驗證數字和小數

因爲我需要給用戶輸入一個數字或十進制值。 Eg: 10 or 1.5 or 30.45

在codeigniter驗證類中,它允許單獨驗證一個數字或十進制數。

有人能告訴我如何在codeigniter中進行驗證嗎?

回答

1
<?php 

class Form extends CI_Controller 
{ 
    public function index() 
    { 
     $this->load->helper(array('form', 'url')); 

     $this->load->library('form_validation'); 

     $this->form_validation->set_rules('weight', 'Weight', 'required|trim|callback_weight_check'); 

     if ($this->form_validation->run() == FALSE) { 
      $this->load->view('myform'); 
     } else { 
      $this->load->view('formsuccess'); 
     } 
    } 

    public function weight_check($val) 
    { 
     if (!is_int($val) || !is_float($val)) { 
      $this->form_validation->set_message('weight_check', 'The {field} field must be number or decimal.'); 
      return FALSE; 
     } else { 
      return TRUE; 
     } 
    } 

} 
0

您可以嘗試建立自己的回調或使用regex_match規則來做到這一點是這樣的:

$this->form_validation->set_rules('cost', 'Cost', array('trim','required','min_length[1]','regex_match[/(^\d+|^\d+[.]\d+)+$/]')); 

你必須使用數組的方式來設置的規則,因爲正則表達式規則使用管道(|)。