CakePHP validation and validation contexts – tình huống validation trong cakePHP


Kiểm tra dữ liệu trong CakePHP 1.2

CakePHP1.1 có kiểu định luật kiểm tra dữ liệu khá là đơn giản, thiếu các tính năng và không phức tạp.

Tuy nhiên CakePHP1.2 ra đời sau một cuộc cách mạng, trong đó có những thay đổi lớn trong Validation class, và phương thức  Model::invalidateFields().

Biến $validate kiểu mới

Cách 1:giống cakePHP1.1

Code:

var $validate = array(

‘fieldName’ => ‘ruleName’

);

Cách 2:Một luật một trường

You can now define more complex rules using the following construct. (Parameters explained later)

Code:

var $validate = array(

‘fieldName’ => array(

‘rule’ => ‘ruleName’ // or ‘rule’ => array(‘ruleName’, ‘param1’, ‘param2’ …)

‘required’ => true,

‘allowEmpty’ => false,

‘on’ => ‘create’,  // or update

‘message’ => ‘Your Error Message’

)

);

Cách 3: nhiều luật cho một trường

Code:

var $validate = array(

‘fieldName’ => array(

‘rule_index’ => array(

‘rule’ => ‘ruleName’ // or ‘rule’ => array(‘ruleName’, ‘param1’, ‘param2’ …)

‘required’ => true,

‘allowEmpty’ => false,

‘on’ => ‘create’, // or update

‘message’ => ‘Your Error Message’

)

)

);

Các cách tham số mới

rule – mixed:

luật hỗn hợp, với nhiều phương án sử dụng khác nhau

Code:

var $validate = array(

‘username’ => array(

‘rule’ => array(‘between’, 6, 20)

)

);

allowEmpty – bool:

cho phép rỗng

required – bool:

luôn yêu cầu nhập

on – string (’create’ or ‘update’):

sử dụng luật khi create dữ liệu, hay update dữ liệu mới.

message – string:

Là thông điệp thông báo lỗi.

Một ví dụ đầy đủ

Code:

var $validate = array(

‘username’ => array(

VALID_NOT_EMPTY,

‘alphanumeric’ => array(

‘rule’ => ‘alphanumeric’,

‘message’ => ‘Username may only consist of letter and numbers’

),

‘length’ => array(

‘rule’ => array(‘between’, 6, 20),

‘message’ => ‘Username must be between 6 and 20 characters in length’

)

),

‘name’ => VALID_NOT_EMPTY,

’email’ => array(   ‘Invalid email format’ => VALID_EMAIL, VALID_NOT_EMPTY ),

‘passwrd’ => array(

VALID_NOT_EMPTY,

‘length’ => array(

‘rule’ => array(‘minLength’, 6),

‘message’ => ‘Password must be at least 6 characters in length’

),

‘strong’ => array(

‘rule’ => ‘isStrong’,

‘message’ => ‘Your password is not strong enough’

)

)

);

http://lemoncake.wordpress.com/2007/07/03/all-about-validation-in-cakephp-12/(nguồn tham khảo)



1 bình luận cho “CakePHP validation and validation contexts – tình huống validation trong cakePHP”

  1. Need more info about Multi stress syllable word? You are welcome!

Bình luận về bài viết này