Yii2验证规则的`when`条件

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

Yii2 Rules Validate When Condition

问题

我使用Yii2生成的表单字段,通过echo $form->field来生成。当我选择'立即支付'并提交时,验证不应验证支付人的姓氏。但是,当我选择'稍后支付'并提交时,它必须验证为必填字段。

无论我选择什么,它总是将该字段视为必填字段。我做错了什么?

选择选项:

  1. <select id="singleregisterform-paymentoptionid" name="SingleRegisterForm[paymentOptionId]">
  2. <option value="1">立即支付</option>
  3. <option value="2">稍后支付</option>
  4. </select>

文本字段:

  1. <input type="text" id="singleregisterform-paymentpersonlastname"
  2. name="SingleRegisterForm[paymentPersonLastname]"
  3. maxlength="40" placeholder="输入姓氏">

Yii2模型规则:

  1. ['paymentOptionId', 'required'],
  2. ['paymentPersonTitleId', 'required'],
  3. ['paymentPersonLastname', 'string', 'min' => 2, 'max' => 45],
  4. ['paymentPersonLastname', 'required', 'when' => function ($model) {
  5. return $model->paymentOptionId == 2;
  6. }, 'whenClient' => "function (attribute, value) {
  7. return $('#paymentOptionId').val() == 2;
  8. }"]
英文:

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:

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

Text Field:

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

Yii2 Model Rules:

  1. [&#39;paymentOptionId&#39;, &#39;required&#39;],
  2. [&#39;paymentPersonTitleId&#39;, &#39;required&#39;],
  3. [&#39;paymentPersonLastname&#39;, &#39;string&#39;, &#39;min&#39; =&gt; 2, &#39;max&#39; =&gt; 45],
  4. [&#39;paymentPersonLastname&#39;, &#39;required&#39;, &#39;when&#39; =&gt; function ($model) {
  5. return $model-&gt;paymentOptionId == 2;
  6. }, &#39;whenClient&#39; =&gt; &quot;function (attribute, value) {
  7. return $(&#39;#paymentOptionId&#39;).val() == 2;
  8. }&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:

确定