Github源码:https://github.com/phalcon/cphalcon/tree/master/phalcon/validation/validator
Phalcon 2.0 Model 字段验证:
public function validation() { $this->validate(new PresenceOf(array( "field" => 'code', "message" => '应用名称不能为空', ))); $this->validate(new Regex(array( "field" => 'code', "message" => '应用名称只能包含字母、数字、 中、下划线', 'pattern' => '/^[-A-Za-z0-9_]+$/', ))); $this->validate(new Model\Validator\Uniqueness(array( 'field' => 'code', 'message' => '应用名称已被使用' ))); $this->validate(new PresenceOf(array( "field" => 'name', "message" => '名称不能为空', ))); $this->validate(new PresenceOf(array( "field" => 'mechanismId', "message" => '请选择归属推理系统', ))); return $this->validationHasFailed() != true; }
Phalcon 3.0 Model 字段验证:
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Regex as RegexValidator;
use Phalcon\Validation\Validator\Uniqueness;
public function validation() { $validator = new Validation(); //验证值不为null或空字符串 $validator->add( [ 'mobile', 'password' ], new PresenceOf([ "message" => [ 'mobile' => '手机号不能为空', 'password' => '密码不能为空', ], ]) ); //允许验证字段的值是否与正则表达式匹配 $validator->add( [ 'mobile', 'password' ], new RegexValidator([ 'pattern' => [ 'mobile' => "/^(13[0-9]|14[0-9]|17[0-9]|15[0-9]|18[0-9])\d{8}$/", 'password' => "/^[A-Za-z0-9_]+$/", ], 'message' => [ 'mobile' => '手机号只能包含英文、数字和下划线', 'password' => '密码只能包含英文、数字和下划线' ] ]) ); //检查相关表中的字段是否唯一 $validator->add( 'mobile', new Uniqueness([ 'model' => 'User', 'message' => ':field must be unique' ]) ); return $this->validate($validator); }