我有以下验证规则:
'lightboard_line_1' => 'required_without_all:lightboard_line_2,lightboard_line_3|min:1|max:10',
'lightboard_line_2' => 'required_without_all:lightboard_line_1,lightboard_line_3|min:1|max:10',
'lightboard_line_3' => 'required_without_all:lightboard_line_1,lightboard_line_2|min:1|max:10',
因此,我们的想法是,当lightboard_line_2
有值时,不再需要lightboard_line_1
和lightboard_line_3
。
由于min
和max
规则,它们目前确实需要一个值。
有没有一种方法可以确保只有当字段有值且需要时才能确定最小值?
字段的HTML代码:
<input name="lightboard_line_1" type="text">
<input name="lightboard_line_2" type="text">
<input name="lightboard_line_3" type="text">
答案 0 :(得分:0)
我会将验证规则更新为:
StopWatch
然后,在根据规则检查规则之前,我会根据完成的输入动态修改规则,例如:
$rules = [
'lightboard_line_1' => 'required_without_all:lightboard_line_2,lightboard_line_3',
'lightboard_line_2' => 'required_without_all:lightboard_line_1,lightboard_line_3',
'lightboard_line_3' => 'required_without_all:lightboard_line_1,lightboard_line_2',
];
这样,if ( $request->has('lightboard_line_1') ) {
// append to the rule
$rules['lightboard_line_1'] .= '|min:1|max:10';
} else if ( ...
和min
仅对已完成的字段强制执行。随意根据需要优化代码。
答案 1 :(得分:0)
我找到了一个解决方案,我现在正在验证使用此代码:
/** @var Validator $validator */
$validator = \Validator::make( $request->request->all(), [
'lightboard_line_1' => 'required_without_all:lightboard_line_2,lightboard_line_3',
'lightboard_line_2' => 'required_without_all:lightboard_line_1,lightboard_line_3',
'lightboard_line_3' => 'required_without_all:lightboard_line_1,lightboard_line_2'
], [
'required_without_all' => __( 'At least line is required' ),
'min' => __( 'Your input should be at least :min characters' ),
'max' => __( 'Your input cannot be more than :max characters' )
] );
$validator->sometimes(
'lightboard_line_1',
'required|min:5|max:10',
function ( $input ) {
return ! empty( $input->lightboard_line_1 );
}
);
$validator->sometimes(
'lightboard_line_2',
'required|min:5|max:10',
function ( $input ) {
return ! empty( $input->lightboard_line_2 );
}
);
$validator->sometimes(
'lightboard_line_3',
'required|min:5|max:10',
function ( $input ) {
return ! empty( $input->lightboard_line_3 );
}
);