cakephp - How to create custom validation for Modelless Forms in cakephp3 -
i want create custom validation fields. form has been extended cakephp form class (modelless forms).
note: bear in mind modelless forms there no table or database.
the problem when create validation give me error.
method isvalidcardnumber not exist
here code:
<?php namespace app\form; use cake\core\configure; use cake\form\form; use cake\form\schema; use cake\network\exception\socketexception; use cake\validation\validator; use sagepay\sagepaydirectpayment; /** * payment form */ class paymentform extends form { /** * define schema * * @param \cake\form\schema $schema schema customize. * @return \cake\form\schema schema use. */ protected function _buildschema(schema $schema) { return $schema ->addfield('name', 'string') ->addfield('card_number', 'string') ... ...; } /** * define validator * * @param \cake\validation\validator $validator validator customize. * @return \cake\validation\validator validator use. */ protected function _buildvalidator(validator $validator) { return $validator ->notempty('name', 'please enter name on card.') ->notempty('card_number', 'string') ->add('card_number', 'isvalidcardnumber', [ 'rule' => ['isvalidcardnumber'], 'message' => 'card number should 16 long number.' ]) ... ...; } protected function isvalidcardnumber($data, array $context) { debug($data); die; } }
you need set provider.
$validator = new validator(); // use object instance. $validator->provider('custom', $myobject); // use class name. methods must static. $validator->provider('custom', 'app\model\validation');
use cake\orm\table; use cake\validation\validator; class userstable extends table { public function validationdefault(validator $validator) { $validator ->add('role', 'validrole', [ 'rule' => 'isvalidrole', // <--- method 'message' => __('you need provide valid role'), 'provider' => 'table', // <--- provider ]); return $validator; } public function isvalidrole($value, array $context) { return in_array($value, ['admin', 'editor', 'author'], true); } }
the code copy pasted official documentation, alter needed use case.
Comments
Post a Comment