【问题标题】:Yii2 - Form validation rules: How to use custom validation function or alternative?Yii2 - 表单验证规则:如何使用自定义验证功能或替代方案?
【发布时间】:2014-07-29 23:29:26
【问题描述】:

我正在使用 Yii 2.0, 我不知道如何验证下拉列表中所选选项的值,我需要检查它是否大于零。

到目前为止我有什么

在规则数组中

['year', 'required'],
['day', 'required'],
['month', 'checkDefaultValue'],...

自定义验证方法是

public function checkDefaultValue() {
    if ($this->month > 0) {
        $this->addError('month', 'Month error message...');
    }
}

此代码不起作用,是否有更好的方法?

【问题讨论】:

  • 您的数组类似于 ["Jan", "Feb"] 或 [0=>JAN, 1=> "Feb"]

标签: php validation yii yii2


【解决方案1】:

你可以这样做

['month', 'in','range' => ['Jan','Feb']],

指定值的范围。

【讨论】:

  • 谢谢,它的工作原理,但如果我需要创建一个条件,如 != 或类似的东西?
【解决方案2】:

您的代码不起作用,因为如果月份大于零,它会添加错误,这与您想要的相反。
这会起作用:

public function checkDefaultValue() {
    if ($this->month <= 0) {
        $this->addError('month', 'Month error message...');
    }
}

或者使用默认的数字验证器来做这个甚至更多:

[
    ['month'], 
    'number', 
    'integerOnly' => true,
    'min' => 1,
    'tooSmall'=>'the selected item is too small for month!!!',
    'max' => 12,
    'tooBig'=>'the selected item is too big for month!!!',
]

【讨论】:

    【解决方案3】:

    你可以使用range验证器,如果你还想做custom validationthis会帮助你。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 2020-07-02
      • 2017-12-01
      • 2011-05-20
      • 2019-11-21
      • 2014-04-22
      相关资源
      最近更新 更多