codecamp

CakePHP的验证

通常情况下,我们建设网站时,需要在进一步处理数据之前验证某些事情。 CakePHP提供了验证包来创建一个可以轻松验证数据的验证器。

验证方法

CakePHP在Validation类中提供了多种的验证方法,最常用的如下。

语法Add  (string  $field  ,  array|string  $name  , array|Cake\Validation\ValidationRule $rule [] ) 
参数说明 -要添加规则的域的字段名;-单条规则或者多条规则数组的别名;-要添加的规则;
返回类型$this
说明为域的规则库添加一条新规则,如果第二个参数为数组,则规则库中的规则都会被第二个参数数组中的规则替代,且第三条规则会被忽略
语法allowEmpty  (string  $field  ,  boolean|string|callable  $when  true  , string|null $message null)
参数说明 -字段名;-显示当前域是否允许为空,有效值为true(总是),create,update。如果传递一个回调函数,此域只在回调函数返回true时留空
返回类型$this
说明允许一个域为空
语法alphanumeric  (string  $field,  string|null  $message  null, string|callable|null $when null) 
参数说明 -要应用规则的域;-规则应用失败时显示的错误信息;-当验证规则被应用时,要么是create,要么是update,要么是返回值为true的回调函数;
返回类型$this
说明为当前域添加一条字母数字混合编排的规则
语法creditCard (string $field , string $type 'all', string|null $message null, string|callable|null $when null) 
参数说明 -要应用规则的域;-允许的信用卡类型,默认为“all”,你也可以提供一个可接受的信用卡类型的数组,如['mastercard','visa','amex']
返回类型$this
说明为当前域添加一个信用卡规则
语法Email (string $field , boolean $checkMX false , string|null $message null , string|callable|null $when null) 
参数说明 -要应用规则的域; -是否检查MX记录;-规则应用失败时显示的错误信息;-当验证规则被应用时,要么是create,要么是update,要么是返回值为true的回调函数;
返回类型$this
说明为当前域添加一个邮件规则
语法maxLength (string $field , integer $max , string|null $message null ,string|callable|null $when null) 
参数说明 -要应用规则的域; -允许的最大长度;-规则应用失败时显示的错误信息;-当验证规则被应用时,要么是create,要么是update,要么是返回值为true的回调函数;
返回类型$this
说明为当前域添加一个字符长度规则
语法minLength (string $field , integer $min , string|null $message null , string|callable|null $when null) 
参数说明 -要应用规则的域; -允许的最小长度;-规则应用失败时显示的错误信息;-当验证规则被应用时,要么是create,要么是update,要么是返回值为true的回调函数;
返回类型$this
说明为当前域添加一个字符长度规则
语法notBlank (string $field , string|null $message null , string|callable|null $when null) 
参数说明 -要应用规则的域;-规则应用失败时显示的错误信息;-当验证规则被应用时,要么是create,要么是update,要么是返回值为true的回调函数;
返回类型$this
说明为当前域添加一个非空规则



CakePHP的安全性
CakePHP创建验证器
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

CakePHP Useful Resources

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }