英文:
Yii2 Rules Validate When Condition
问题
我使用Yii2生成的表单字段,通过echo $form->field
来生成。当我选择'立即支付'并提交时,验证不应验证支付人的姓氏。但是,当我选择'稍后支付'并提交时,它必须验证为必填字段。
无论我选择什么,它总是将该字段视为必填字段。我做错了什么?
选择选项:
<select id="singleregisterform-paymentoptionid" name="SingleRegisterForm[paymentOptionId]">
<option value="1">立即支付</option>
<option value="2">稍后支付</option>
</select>
文本字段:
<input type="text" id="singleregisterform-paymentpersonlastname"
name="SingleRegisterForm[paymentPersonLastname]"
maxlength="40" placeholder="输入姓氏">
Yii2模型规则:
['paymentOptionId', 'required'],
['paymentPersonTitleId', 'required'],
['paymentPersonLastname', 'string', 'min' => 2, 'max' => 45],
['paymentPersonLastname', 'required', 'when' => function ($model) {
return $model->paymentOptionId == 2;
}, 'whenClient' => "function (attribute, value) {
return $('#paymentOptionId').val() == 2;
}"]
英文:
I have form fields generated by Yii2 using echo $form->field. When I select 'Pay Now' and submit, the validation should NOT validate the payment person's last name. However, when I select 'Pay Later' and submit, it must validate it as required.
Regardless of what I select, it always treats the field as required. What am I doing wrong?
Select Option:
<select id="singleregisterform-paymentoptionid" name="SingleRegisterForm[paymentOptionId]">
<option value="1">Pay Now</option>
<option value="2">Pay Later</option>
</select>
Text Field:
<input type="text" id="singleregisterform-paymentpersonlastname"
name="SingleRegisterForm[paymentPersonLastname]"
maxlength="40" placeholder="Enter last name">
Yii2 Model Rules:
['paymentOptionId', 'required'],
['paymentPersonTitleId', 'required'],
['paymentPersonLastname', 'string', 'min' => 2, 'max' => 45],
['paymentPersonLastname', 'required', 'when' => function ($model) {
return $model->paymentOptionId == 2;
}, 'whenClient' => "function (attribute, value) {
return $('#paymentOptionId').val() == 2;
}"],
答案1
得分: 1
你需要添加一个'whenClient'规则。
链接:https://www.yiiframework.com/doc/guide/2.0/en/input-validation#conditional-validation
英文:
You need to add a ‘whenClient’ rule
https://www.yiiframework.com/doc/guide/2.0/en/input-validation#conditional-validation
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论