1、实现一个获取文章列表的接口,需要基于日期控件查询数据,如图1
2、验证规则配置如下
['from_created_at', 'datetime', 'format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'from_created_at', 'on' => 'index'], //index ['to_created_at', 'datetime', 'format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'to_created_at', 'on' => 'index'], //index ['from_created_at', 'compare', 'compareAttribute' => 'to_created_at', 'operator' => '<', 'enableClientValidation' => false], //index
3、from_created_at、to_created_at皆为空,验证通过,如图2
4、日期(datetime,例:2017-03-03 12:05:54):from_created_at、to_created_at;验证不通过,如图3
{ "code": 20004, "message": "数据验证失败:属性 From Created At 的格式无效。" }
5、比对日期值(from_created_at < to_created_at):from_created_at, to_created_at;验证不通过,如图4
{ "code": 20004, "message": "数据验证失败:From Created At的值必须小于/"To Created At/"。" }
6、如果from_created_at不为空,to_created_at为空,验证不通过,如图5
{ "code": 20004, "message": "数据验证失败:From Created At的值必须小于/"To Created At/"。" }
7、如果from_created_at为空,to_created_at不为空,验证通过,不符合预期,预期:或者皆为空,或者皆不为空
8、验证规则配置如下,只有在一个日期值不为空时,才验证另一个日期值为必填
['from_created_at', 'datetime', 'format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'from_created_at', 'on' => 'index'], //index ['to_created_at', 'datetime', 'format' => 'php:Y-m-d H:i:s', 'timestampAttribute' => 'to_created_at', 'on' => 'index'], //index ['from_created_at', 'required', 'when' => function($model) { return !empty($model->to_created_at); }], //index ['to_created_at', 'required', 'when' => function($model) { return !empty($model->from_created_at); }], //index ['from_created_at', 'compare', 'compareAttribute' => 'to_created_at', 'operator' => '<', 'enableClientValidation' => false], //index
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/180979.html