CakePHP-验证可以为空,但如果不为空,则至少需要4个字符&;数字的
如何创建允许字段为空的验证规则,但如果字段为空,则需要为数字且长度为4个字符 这就是我现在拥有的CakePHP-验证可以为空,但如果不为空,则至少需要4个字符&;数字的,cakephp,Cakephp,如何创建允许字段为空的验证规则,但如果字段为空,则需要为数字且长度为4个字符 这就是我现在拥有的 'year' => array( 'numeric' => array( 'rule' => 'numeric', 'message' => 'Numbers only' ), 'maxLength' => array( 'rule' => ar
'year' => array(
'numeric' => array(
'rule' => 'numeric',
'message' => 'Numbers only'
),
'maxLength' => array(
'rule' => array('maxLength', 4),
'message' => 'Year in YYYY format'
),
'minLength' => array(
'rule' => array('minLength', 4),
'message' => 'Year in YYYY format'
)
)
这很好,但是当字段为空时,它仍然运行验证
谢谢,Tee下面的代码片段应该可以做到这一点:
'numeric' => array(
'rule' => 'numeric',
'allowEmpty' => true,
'message' => 'Numbers only'
),
另请参见烹饪手册中关于的章节。您还忘记了最后一个=>真参数-有关详细信息,请参见。最后一个属性应改为false=>。因此,最终的解决方案应该如下所示:
'year' => array(
'numeric' => array(
'rule' => 'numeric',
'allowEmpty' => true,
'message' => 'Numbers only'
'last' => false ), ...
我个人喜欢把事情分开(可读性更强,调试更容易):
有一种方法可以简单地做到这一点
array(
'myfield' => array(
"rule_empty" => array(
'rule' => '#.*#i', // validate everything
'allowEmpty' => true,
'last' => false
),
"rule_price" => array(
'message' => 'Is not a valid price ! ',
'rule' => "\/^[0-9]+(?:(\\.|,)[0-9]{1,})?$\/"
)
)
);
我还想提出至少一个必需的规则。在上面我该怎么做?我正在使用一个输入数组字段。
'numeric' => array(
'rule' => 'numeric',
'message' => 'Numbers only'
),
'maxLength' => array(
'rule' => array('maxLength', 10),
'message' => '10 digit no'
)
array(
'myfield' => array(
"rule_empty" => array(
'rule' => '#.*#i', // validate everything
'allowEmpty' => true,
'last' => false
),
"rule_price" => array(
'message' => 'Is not a valid price ! ',
'rule' => "\/^[0-9]+(?:(\\.|,)[0-9]{1,})?$\/"
)
)
);