[英]Cakephp 3.0 Form validation
I'm playing around with Cakephp 3.0 and wondering how I go about validating data which is not being saved to the database. 我正在玩Cakephp 3.0,想知道如何验证未保存到数据库的数据。
For example I know in the model (which appears to be now known as a "table") you add a validationDefault method to the model which is called automatically when data is being saved to the database ie a new user is being added to the database. 例如,我知道在模型(现在似乎称为“表”)中,您向模型添加了一个validationDefault方法,当将数据保存到数据库时即自动将新用户添加到数据库时,该方法会自动调用。 But how would I go about validating data from a login form which is not saving to the database and then show those errors? 但是,我将如何验证未保存到数据库的登录表单中的数据,然后显示这些错误?
For example on a user login, I would want to check whether fields have been entered, doesn't exceed a certain size etc 例如,在用户登录时,我想检查是否已输入字段,未超过特定大小等
Taken from the official docs, you can instantiate a validator in your controller and validate your data by passing it $this->request->data()
取自官方文档,您可以在控制器中实例化验证器,并通过将其传递给$this->request->data()
验证数据。
use Cake\Validation\Validator;
...
$validator = new Validator();
$validator
->validatePresence('email')
->add('email', 'validFormat', [
'rule' => 'email',
'message' => 'E-mail must be valid'
])
->validatePresence('name')
->notEmpty('name', 'We need your name.')
->validatePresence('comment')
->notEmpty('comment', 'You need to give a comment.');
$errors = $validator->errors($this->request->data());
if (!empty($errors)) {
// Send an email.
}
http://book.cakephp.org/3.0/en/core-libraries/validation.html http://book.cakephp.org/3.0/en/core-libraries/validation.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.