Codeigniter3-FormValidation-验证布尔值始终为“ false”

时间:2019-11-26 20:30:30

标签: validation boolean codeigniter-3

我正在使用Codeigniters本机FormValidation库检查JSON输入数据。 我已经设置了如下验证规则:

$this->form_validation->set_rules(
      'active', 'myCheckbox', 
      'required|is_bool'
);

这是JSON数据

    {
      "data": {
      "type": "items",
      "attributes": {
        "category": "5",
        "description" : "my description",
        "active": false
       }
      }
    }

问题::只要active的JSON值为false,规则“ required”就会将输入解释为不存在,因此验证仅在value为active中的true

问题:除了将active的值更改为numeric的值10之外,还有解决方法吗?很多其他对应代码?

编辑:尝试使用isset而不是required的行为有所不同,但也不令人满意

 $this->form_validation->set_rules(
      'active', 'myCheckbox', 
      'isset|is_bool'
);

编辑No.2:尝试使用in_list[false,true]而不是is_bool的行为是正确的,但是JSON看起来不再正确,因为布尔值必须作为字符串发送

$this->form_validation->set_rules(
      'active', 'myCheckbox', 
      'required|in_list[false,true]'
);

这是JSON数据

{
  "data": {
  "type": "items",
  "attributes": {
    "category": "5",
    "description" : "my description",
    "active": "false"
   }
  }
}

1 个答案:

答案 0 :(得分:0)

我有同样的问题。 我修复了它,创建了自己的“必需”和我自己的“ is_bool”。 我创建了一个“ is_required_not_null”和“ is_boolean”函数,然后将其放入助手中,因此可以在需要的地方使用它。 请注意,我使用了Identical运算符(===)来确定变量的类型和值。 见下文...

帮助文件: /yourApplication/helpers/yourHelperFileName_helper.php

    $data = $this->input->post(); //yours inputs ...

    $rules = [          
        [
            'field' => 'fieldName',
            'rules' => 'is_required_not_null|is_boolean',
            'label' => 'Field Name',
            'errors' => [
                'is_required_not_null' => 'Field %s is required.',
                'is_boolean' => 'Field %s must be boolean.',
            ],
        ],
    ]; //yours rules ...

    $this->load->library('form_validation');
    $this->form_validation->set_data($data);
    $this->form_validation->set_rules($rules);

    if ($this->form_validation->run()) {
        //Valid Code ...
    }
    else{
        //Not Valid Code ...
    }

使用示例:

list_ = [1,2,3,4,5]
total = sum(list_)
length = len(list_)
acc = 0
out = []
for i, v in enumerate(list_):
    acc += v
    result = v*(length-(i+1)) - (total - acc)
    out.append(result)

原始文档:

https://codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post

https://codeigniter.com/userguide3/libraries/form_validation.html#setting-rules-using-an-array

https://codeigniter.com/userguide3/libraries/form_validation.html#callable-use-anything-as-a-rule

https://codeigniter.com/userguide3/libraries/form_validation.html#setting-validation-rules