【问题标题】:float Number validation check for codeigniter浮点数验证检查 codeigniter
【发布时间】:2012-12-14 06:17:34
【问题描述】:

在这里,我以 % 输入税金字段,但是当我输入 2.5、0.5 等除整数以外的值时,它会产生错误。 这是我的验证代码,输入浮点数的任何想法

函数 _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');
}
函数 max_pst()
 {
   if($this->input->post('pst')>100)
    {
      $this->form_validation->set_message('max_pst',' %s 值应该小于等于100');
返回错误;
    }
   返回真;
  }
函数 max_gst()
  {
    if($this->input->post('gst')>100)
      {
    $this->form_validation->set_message('max_gst',' %s 值应该小于等于100');
    返回错误;
    }
   返回真;
  }

【问题讨论】:

  • 任何事情,任何提示都会起作用
  • 尝试从验证规则中删除is_natural
  • @Moes 如您所见,我已将 is_natural 验证用于不允许负数,所以我收到错误,就像您只能输入正数一样
  • 然后是不允许负数的任何其他方式
  • 我会使用 greater_than[0]less_than[100] 并删除 is_natural

标签: php codeigniter validation numbers


【解决方案1】:

来自 codeigniter 文档:

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

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

希望对你有帮助!

【讨论】:

  • 谢谢,我会试试这个,很快就会回来
【解决方案2】:

从验证规则中删除is_natural,并将其替换为greater_than[0]less_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

【讨论】:

    【解决方案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;
        }
    }
    

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

    【讨论】:

    • 谢谢,我会试试这个,很快就会回来
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2015-07-14
    • 1970-01-01
    • 2020-03-16
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    相关资源
    最近更新 更多