如何为应在cakephp 3.0中选中的复选框创建验证
在cakephp 2.x中,验证过程如下:
'accept_terms' => array(
'rule' => array('comparison', '!=', 0),
'required' => true,
'message' => 'You must agree to the terms',
'on' => 'create',
),我想把它转换成cakephp 3.x。
发布于 2019-05-26 00:11:48
在CakePHP 3.x中
表单
<?= $this->Form->create($user) ?>
<?= $this->Form->control('username'); ?>
<?= $this->Form->control('password'); ?>
...
<?= $this->Form->control('term_and_conditions'); ?>
<?= $this->Form->submit(__('Save')); ?>
<?= $this->Form->end(); ?>模型:验证器::equals($field,$value,$message = null,$when = null)允许您检查是否选中了某个复选框
public function validationDefault(Validator $validator)
{
...
$validator
->boolean('term_and_conditions')
->requirePresence('term_and_conditions', 'create')
->equals('term_and_conditions', true);
...
return $validator;
}发布于 2015-12-15 19:40:29
没有用于验证复选框的特殊规则。您要做的是验证字段在create上是否为notEmpty:-
$validator
->requirePresence('accept_terms')
->notEmpty('accept_terms', 'You must agree to the terms', 'create');这可以在official docs on Validation中找到。可用验证规则的完整列表可以是found in the API docs。
发布于 2016-03-03 12:10:47
您可以使用自定义方法来验证您的复选框。我真的喜欢这样。这对我来说是可以的。
public function validationBooking(Validator $validator)
{
$validator->add('accept_terms', 'custom', [
'rule' => [$this, 'AcceptTerm'],
'message' => 'You must agreed Term and Condition'
]);
return $validator;
}
//make function
public function AcceptTerm($value,$context){
if($context['data']['accept_terms']==1)
return true;
else
return false;
}https://stackoverflow.com/questions/34287381
复制相似问题