【问题标题】:Both string and integer rules for a filed in laravel validationlaravel 验证中字段的字符串和整数规则
【发布时间】:2019-08-09 05:55:51
【问题描述】:

我想验证一个可以是整数或字符串的字段。

当为整数时,最大值必须小于30,当为字符串时,最大值不能超过10个字符。

有什么方法可以在不制定自定义规则的情况下解决?如果不是,那么创建此规则的最佳算法是什么?

【问题讨论】:

    标签: laravel validation


    【解决方案1】:

    试试这样的:

    $validator = Validator::make($request->all(), [
        'title' => [
            'required',
            function ($attribute, $value, $fail) {
                if (is_int($value) && $value > 30) {
                    $fail($attribute . ' must be less than 30.');
                } else if (is_string($value) && strlen($value) > 10 ) {
                    $fail($attribute . ' must be less than 10 characters.');
                }
            },
        ],
    ]);
    

    请参阅 Laravel documentation 了解更多信息。

    【讨论】:

      猜你喜欢
      • 2015-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-29
      • 1970-01-01
      • 2017-02-06
      相关资源
      最近更新 更多