Laravel 5.3 - 验证规则min和required_if问题

时间:2016-11-22 23:00:50

标签: laravel laravel-5 laravel-5.3

因此,在Request我们进行了一些验证,其中type字段为review,这意味着body字段必须至少包含6个字符。

public function rules(){
     return [
       'type' => 'required|in:star_rating,review',
       'body' => 'required_if:type,review|min:6'
     ];
 }

但问题是,当typestar_rating时,我收到错误The body must be at least 6 characters.

这不应该发生,因为正文是可选的,只有在min:6type review时才需要min:6验证。即使typestar_rating,我也无法弄清楚为什么会对其进行{{1}}验证。

知道如何让它按预期工作吗?

2 个答案:

答案 0 :(得分:2)

如果没有看到更多的逻辑,我无法确定您希望如何继续。但是下面的概念应该让你前进。

根据您定义的参数conditionally adds rules。在您的情况下,如果 @interface ViewController () <...UITextViewDelegate,UITextFieldDelegate...> { UIAlertController *alertTypeAlertController; UIAlertAction *alertType1Action; UIAlertAction *alertType2Action; UIPopoverPresentationController *popPresenter; } - (void)viewDidLoad { [super viewDidLoad]; alertTypeAlertController = [UIAlertController alertControllerWithTitle:@"selecte one:" message:nil preferredStyle:UIAlertControllerStyleActionSheet]; alertType1Action = [UIAlertAction actionWithTitle:@"Type1" style:UIAlertActionStyleDefault handler:nil]; alertType2Action = [UIAlertAction actionWithTitle:@"Type2" style:UIAlertActionStyleDefault handler:nil]; [alertTypeAlertController addAction: alertType1Action]; [alertTypeAlertController addAction: alertType2Action]; // for ipad popPresenter = [alertTypeAlertController popoverPresentationController]; popPresenter.permittedArrowDirections = UIPopoverArrowDirectionLeft; popPresenter.delegate = self; popPresenter.sourceView = self.theTypeBtn; popPresenter.sourceRect = CGRectMake(230, 22, 10, 10); .... } - (void)popoverPresentationControllerDidDismissPopover:(UIPopoverPresentationController *)popoverPresentationController { // called when a Popover is dismissed } - (BOOL)popoverPresentationControllerShouldDismissPopover:(UIPopoverPresentationController *)popoverPresentationController { // return YES if the Popover should be dismissed // return NO if the Popover should not be dismissed return YES; } -(UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller { return UIModalPresentationNone; } enter code here body,则只需要type,如果再次review,则还应用min6字符规则是type

review

答案 1 :(得分:0)

我有同样的问题,CamelCase的答案效果很好! 但我必须将验证逻辑放回我的控制器,因为我的尝试是将此验证逻辑放在Request中。

所以这是另一个解决方案,其中Request中的条件规则适用于Laravel 5.4

public function rules()
    {
        // general rules
        $rules = [
            'type' => 'required|in:star_rating,review',                
        ];

        // conditional rules
        if($this->input('type') == 'review'){
            $rules['body'] = 'required | min:6';
        }

        return $rules;
    }