首页 > 解决方案 > Yii2 : 至少需要两个字段之一

问题描述

必须提供两个电话号码phone_parentphone_students 之一,并且它们必须是整数。组合时,只有 atLeastValidator 有效,当我忽略它时,整数有效。没有想法。有什么提示吗?

[['phone_parent', 'phone_student'], 'integer'],
['phone_student', AtLeastValidator::class, 'in' => ['phone_student', 'phone_parent']],
['phone_parent', AtLeastValidator::class, 'in' => ['phone_student', 'phone_parent']],

更新:当我尝试提交时,我刚刚发现整数有效(还没有发送请求,我仍然在表单页面上);然而,它应该专注于焦点——就像所有其他验证器一样;它是 ActiveForm 的一个实例。

标签: yii2

解决方案


我认为您不需要该 custom AtLeastValidator,您可以使用whenandwhenClient以下列方式按照您想要的方式工作。

您的规则应如下所示

[
    ['phone_parent'],
    'required',
    'when' => function ($model) {
        return ($model->phone_student == '');
    },
    'whenClient' => 'function(attribute,value){
        return ($("#testform-phone_student").val()=="");
    }',
    'message' => 'Either Parent or Student Phone must be filled',
],
[
    ['phone_student'],
    'required',
    'when' => function ($model) {
        return ($model->phone_parent == '');
    },
    'whenClient' => 'function(attribute,value){
        return ($("#testform-phone_parent").val()=="");
    }',
    'message' => 'Either Parent or Student Phone must be filled',
],
[['phone_parent', 'phone_student'], 'integer'],

最重要的是,我会使用正则表达式来验证电话号码是否有效,而不是仅仅使用integer0作为无效的 pone 号码或手机号码。在 中使用match 带有正则表达式的验证器pattern将使其可靠。


推荐阅读