我正在尝试使用cakephp模型实现表单验证。这是我的代码片段......
模型
// File: /app/models/enquiry.php
class Enquiry extends AppModel {
var $name = "Enquiry";
var $useTable = false;
var $_schema = array(
"name" => array( "type" => "string", "length" => 100 ),
"phone" => array( "type" => "string", "length" => 30 ),
"email" => array( "type" => "string", "length" => 255 )
);
var $validate = array(
"name" => array(
"rule" => array( "minLength" => 1 ),
"message" => "Name is required"
),
"email" => array(
"emailFormat" => array( "rule" => "notEmpty", "last" => true, "message" => "Email is required" ),
"emailNeeded" => array( "rule" => array( "email", true ), "message" => "Must be a valid email address" )
)
);
}
控制器操作
// /app/controllers/nodes_controller.php
class NodesController extends AppController {
var $name = "Nodes";
var $uses = array( "Enquiry" );
function enquire() {
if ( $this->data ) {
$this->Enquiry->set( $this->data );
$this->Enquiry->set( "data", $this->data );
if ( $this->Enquiry->validates(
array( "fieldList" => array("name", "email") )
) ) {
// .....
}
}
}
}
查看...
// /app/views/nodes/enquire.ctp
<?php echo $form->create("Node", array("action" => "ask")); ?>
<?php echo $form->input( "name", array( "label" => "Name" ) ); ?>
<?php echo $form->input( "email", array( "label" => "Email" ) ); ?>
<?php echo $form->input( "phone", array( "label" => "Phone" ) ); ?>
<?php echo $form->end("Send");?>
我的问题:提交时,表单永远无法验证。即使我没有在表单中输入任何内容,validate函数每次都返回true。
我做错了什么?
此致
答案 0 :(得分:1)
我认为您将错误的数据传递给验证。设置$this->data
后,我只需要调用
$this->Model->validates();
// or
$this->Model->validates($this->data);
答案 1 :(得分:1)
由于您只有两个验证规则,因此无法列出要在validates()
中验证的两个字段。试试这个:
function enquire(){
if($this->data){
$this->Enquiry->set( this->data);
if($this->Enquiry->validates()){
// it validated logic
}else{
// didn't validate logic
}
}
}
您的验证数组应该是(遵循语法一致性):
var $validate = array(
'name' => array(
'notEmpty' => array(
'rule' => 'notEmpty',
'message' => 'Name is required'
)
),
'email' => array(
'emailFormat' => array(
'rule' => 'notEmpty',
'message' => 'Email is required'
),
'emailNeeded' => array(
'rule' => array('email', true),
'message' => 'Must be a valid email address'
)
)
);