3

在这里,我以 % 输入税收字段,但是当我输入 2.5,0.5 之类的值而不是整数时,它会产生错误。这是我的验证代码,输入浮点数的任何想法

function _set_rules()
{
  $this->form_validation->set_rules('pst','PST','trim|required|is_natural|numeric|
   max_length[4]|callback_max_pst');
  $this->form_validation->set_rules('gst','GST','trim|required|is_natural|numeric|
max_length[4]|callback_max_gst');
}
function max_pst()
 {
   if($this->input->post('pst')>100)
    {
      $this->form_validation->set_message('max_pst',' %s Value Should be less than or equals to 100');
return FALSE;
    }
   return TRUE;
  }
function max_gst()
  {
    if($this->input->post('gst')>100)
      {
    $this->form_validation->set_message('max_gst',' %s Value Should be less than or equals to 100');
    return FALSE;
    }
   return TRUE;
  }
</code>
4

3 回答 3

15

从验证规则中删除并将is_natural其替换为greater_than[0]andless_than[100]

function _set_rules()
{
  $this->form_validation>set_rules('pst','PST','trim|required|
  greater_than[0]|less_than[100]|max_length[4]|callback_max_pst');
  $this->form_validation->set_rules('gst','GST','trim|required|
  greater_than[0]|less_than[100]|max_length[4]|callback_max_gst');
}

greater_than[0]将应用numeric

于 2012-12-29T04:57:11.837 回答
3

从 codeigniter 文档中:

is_natural如果表单元素包含自然数以外的任何内容,则返回 FALSE:0、1、2、3 等。

显然,像 2.5,0.5 这样的值不是自然数,因此它们将无法通过验证。floatval()您可以使用回调并在使用PHP 函数解析值后返回值。

希望能帮助到你!

于 2012-12-29T04:50:54.060 回答
3

你可以试试这个:

function _set_rules()
{
  $this->form_validation>set_rules('pst','PST','trim|required|
  numeric|max_length[4]|callback_max_pst');
  $this->form_validation->set_rules('gst','GST','trim|required|
  numeric|max_length[4]|callback_max_gst');
}

function max_pst($value) {
    $var = explode(".", $value);
    if (strpbrk($value, '-') && strlen($value) > 1) {
        $this->form_validation->set_message('max_pst', '%s accepts only 
        positive values');
        return false;
    }
    if ($var[1] > 99) {
        $this->form_validation->set_message('max_pst', 'Enter value in 
        proper format');
        return false;
    } else {
        return true;
    }
}

希望这段代码对您有所帮助.... :)

于 2012-12-29T04:51:29.917 回答