yii2 - 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 的一个实例。
解决方案
我认为您不需要该 custom AtLeastValidator
,您可以使用when
andwhenClient
以下列方式按照您想要的方式工作。
您的规则应如下所示
[
['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
作为无效的 pone 号码或手机号码。在 中使用match
带有正则表达式的验证器pattern
将使其可靠。
推荐阅读
- java - 在 Docker 中运行 Selenium 测试时,连接被拒绝的 UnreachableBrowserException
- c# - 通过 XAML 实例化视图时 SimpleInjector.Container.Verify 中的 NullReferenceException
- c++ - 此 BTC 代码如何验证用户输入?
- excel - VBA转到范围内的下一个空白单元格
- apache-nifi - 如何在 NiFi 中查找特定进程组的数据量大小?
- python - 如何在屏幕上均匀地平铺 matplotlib 图形?
- html - 正确对齐在 bootsrap 导航栏中不起作用
- sql-server - ORA-00997 非法使用 Long 数据类型 Oracle DBlink-msSQLserver
- python - 如何将张量流图分成两部分并将它们保存到两个saved_model?
- python - 如何在 seaborn 的 catplot 中添加网格线?