[['shortcode'],'string', 'length' => [8, 11]],// first
['shortcode','required', // second
'when' => function($model) {
// code here
},
],
如果我将规则length
设置为required
,我如何合并我的规则def create
customer = Customer.new(customer_params)
respond_to do |format|
format.json do
if customer.save
render json: customer, status: :created, , location: api_v1_customer_url(@customer
else
render json: customer.errors, status: :unprocessable_entity
end
end
end
end
?提前致谢。
现在,我总是最终检查最小长度。
答案 0 :(得分:1)
最佳选择(应始终使用)是使用scenarios。我不知道任何其他解决方案,只有场景。如果您还没有使用它,请按照以下方式实施:
public function scenarios()
{
return [
'scenario_global' => [<attributes list you want to validate>],
'scenario_shortcode_only' => ['shortcode']
];
}
public function rules()
{
return [
[['shortcode'], 'string', 'length' => [8, 11], 'on' => 'scenario_shortcode_only'],
[['shortcode'], 'required', 'on' => 'scenario_shortcode_only'],
// If you need shortcode with different rule set, then use 'except' instead of 'on'
];
}
当您声明方案scenario_shortcode_only
时,只有那些'on' => 'scenario_shortcode_only'
的规则才会被验证,而其他规则将被忽略。