这里是 CakePHP 的新手 - 我正在浏览站点上的文档,试图为我正在创建的模型收集一些基本数据验证。这可能是我对 CakePHP 提出的许多问题中的第一个。
在CakePHP Book ,验证规则似乎指定了两种不同的方法来确保字段不为空 - AllowEmpty
, 和 NotEmpty
.
问题 - 这两者之间有明显的区别吗? CakePHP 指出验证规则应该出现在您的模型或 Controller 中——一个更适合模型,另一个更适合 Controller ?这本书对此没有任何说明。我猜这是一种仍然存在的旧方法?
什么给了?我应该使用特定的一个,还是两者都使用,或者这无关紧要?
编辑:我决定检查 CakePHP 1.3 class documentation对于它(检查 allowEmpty
属性的默认值),但它甚至没有显示。它不在 source code 中要么……有什么我想念的吗?
最佳答案
欢迎来到蛋糕。我希望你喜欢它。
这绝对是 Cake 比较奇怪的方面之一。
notEmpty
本身就是一个规则。您可以在 $validation
属性中定义它。您可以为验证失败时分配一条消息。您可以将其视为任何其他验证规则。
allowEmpty
是另一个验证规则的选项,通常是not notEmpty
。 它本身不是验证规则。例如,这将允许您定义 varchar
字段允许空字符串,'',或不超过 20 个字符的字符串。
编辑:
这是一些代码
// model validation using 'notEmpty'
$validation = array(
'fieldName' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'This value may not be left empty!'
),
... // other rules can go here
),
... // other fieldName can go here
);
// model validation using 'allowEmpty' to create an optional field
$validation = array(
'fieldName' => array(
'maxLength' => array(
'rule' => array('maxLength', 20),
'message' => 'This field may only contain 20 characters!',
'allowEmpty' => true // we'll also accept an empty string
),
... // other rules can go here
)
... // other fieldName can go here
);
关于php - AllowEmpty 与 NotEmpty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6553726/