Codeigniter浮点数验证检查

3

我在输入税收字段时,使用2.5、0.5等整数以外的值会生成错误。以下是我的验证代码,请问如何输入浮点数?

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()
 {
   if($this->input->post('pst')>100)
    {
      $this->form_validation->set_message('max_pst','%s值应小于或等于100');
return FALSE;
    }
   return TRUE;
  }
function max_gst()
  {
    if($this->input->post('gst')>100)
      {
    $this->form_validation->set_message('max_gst','%s值应小于或等于100');
    return FALSE;
    }
   return TRUE;
  }
</code>

任何东西,任何提示都可以。 - Nishant Lad
1
尝试从验证规则中删除 is_natural - Nerdroid
@Moes,你可以看到我已经添加了is_natural验证以防止输入负数,所以我会收到错误提示,告诉我只能输入正数。 - Nishant Lad
禁止负数的另一种方法是什么? - Nishant Lad
1
我会使用 greater_than[0]less_than[100],并移除 is_natural - Nerdroid
尝试使用 greater_than[0] 或在此处查找参考资料:http://ellislab.com/codeigniter/user-guide/libraries/form_validation.html#rulereference - Saleem
3个回答

15

从验证规则中删除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;
    }
}

希望这段代码能帮到您.... :)

3

来自CodeIgniter文档:

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

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

希望这有所帮助!


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接