Yii2:至少需要两个字段之一

时间:2019-08-20 06:17:43

标签: yii2

必须提供两个电话号码之一 phone_parent phone_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的实例。

1 个答案:

答案 0 :(得分:1)

我认为您不需要该自定义AtLeastValidator,您可以通过以下方式使用whenwhenClient来实现所需的工作方式。

您的规则应如下所示

[
    ['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'],

首先,我将使用正则表达式来验证电话号码是否有效,而不是仅使用允许integer作为无效电话号码或手机号码的0。在match中使用带有正则表达式的pattern验证程序将使其牢固。