Yii2 uses the core validator: compare the date value, add a new verification rule (conditional verification: when one date value is not empty, another date value is required)
1. To implement an interface to obtain the list of articles, you need to query the data based on the date control, as shown in Figure 1
2. The configuration of the verification rules is as follows
['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 are all empty, the verification is passed, as shown in Figure 2
4. Date (DateTime, example: 2017-03-03 12:05:54): FROM_CREATED_AT, TO_CREATED_AT; the verification fails, as shown in Figure 3
{
"code": 20004,
"message": "数据验证失败:属性 From Created At 的格式无效。"
}
5. Compare the date value (from_created_at < to_created_at): FROM_created_at, to_created_at; the verification fails, as shown in Figure 4
{
"code": 20004,
"message": "数据验证失败:From Created At的值必须小于\"To Created At\"。"
}
6. If from_created_at is not empty, to_created_at is empty, the verification does not pass, as shown in Figure 5
{
"code": 20004,
"message": "数据验证失败:From Created At的值必须小于\"To Created At\"。"
}
7. If from_created_at is empty, to_created_at is not empty, the verification is passed, does not meet the expectations, expected: or both are empty, or none are empty
8. The verification rules are configured as follows, only when one date value is not empty, the other date value is required
['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




