Yii2验证规则的`when`条件

huangapple go评论56阅读模式
英文:

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:

&lt;select id=&quot;singleregisterform-paymentoptionid&quot; name=&quot;SingleRegisterForm[paymentOptionId]&quot;&gt;
    &lt;option value=&quot;1&quot;&gt;Pay Now&lt;/option&gt;
    &lt;option value=&quot;2&quot;&gt;Pay Later&lt;/option&gt;
&lt;/select&gt;

Text Field:

&lt;input type=&quot;text&quot; id=&quot;singleregisterform-paymentpersonlastname&quot; 
       name=&quot;SingleRegisterForm[paymentPersonLastname]&quot; 
       maxlength=&quot;40&quot; placeholder=&quot;Enter last name&quot;&gt;

Yii2 Model Rules:

[&#39;paymentOptionId&#39;, &#39;required&#39;],
[&#39;paymentPersonTitleId&#39;, &#39;required&#39;],
[&#39;paymentPersonLastname&#39;, &#39;string&#39;, &#39;min&#39; =&gt; 2, &#39;max&#39; =&gt; 45],
[&#39;paymentPersonLastname&#39;, &#39;required&#39;, &#39;when&#39; =&gt; function ($model) {
		return $model-&gt;paymentOptionId == 2;
	}, &#39;whenClient&#39; =&gt; &quot;function (attribute, value) {
		return $(&#39;#paymentOptionId&#39;).val() == 2;
}&quot;],

答案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

huangapple
  • 本文由 发表于 2023年2月18日 07:40:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75490171.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定