Laravel: validate an integer field that needs to b

2019-01-10 20:46发布

I have two fields that are optional only if both aren't present:

$rules = [
  'initial_page' => 'required_with:end_page|integer|min:1|digits_between: 1,5',
  'end_page' => 'required_with:initial_page|integer|min:2|digits_between:1,5'
]; 

Now, end_page needs to be greater than initial_page. How include this filter?

5条回答
再贱就再见
2楼-- · 2019-01-10 21:03

Why not just define $min_number = $min + 1 number and use validator min:$min_number, example:

$min = intval($data['min_number']) + 1;

return ['max_number'  => 'required|numeric|min:'.$min];

And you can then return custom error message to explain the error to user.

查看更多
The star\"
3楼-- · 2019-01-10 21:04

For Laravel 5.4 it will be:

$rules = ['end_page'=>'min:'.(int)$request->initial_page]
查看更多
【Aperson】
4楼-- · 2019-01-10 21:11

There is no built-in validation that would let you compare field values like that in Laravel, so you'll need to implement a custom validator, that will let you reuse validation where needed. Luckily, Laravel makes writing custom validator really easy.

Start with defining new validator in yor AppServiceProvider:

class AppServiceProvider extends ServiceProvider
{
  public function boot()
  {
    Validator::extend('greater_than_field', function($attribute, $value, $parameters, $validator) {
      $min_field = $parameters[0];
      $data = $validator->getData();
      $min_value = $data[$min_field];
      return $value > $min_value;
    });   

    Validator::replacer('greater_than_field', function($message, $attribute, $rule, $parameters) {
      return str_replace(':field', $parameters[0], $message);
    });
  }
}

Now you can use your brand new validation rule in your $rules:

$rules = [
  'initial_page' => 'required_with:end_page|integer|min:1|digits_between: 1,5',
  'end_page' => 'required_with:initial_page|integer|greater_than_field:initial_page|digits_between:1,5'
]; 

You'll find more info about creating custom validators here: http://laravel.com/docs/5.1/validation#custom-validation-rules. They are easy to define and can then be used everywhere you validate your data.

查看更多
时光不老,我们不散
5楼-- · 2019-01-10 21:15

As of Laravel 5.6 gt, gte, lt and lte rules are added.

查看更多
再贱就再见
6楼-- · 2019-01-10 21:23

I think you can try something like this,

$init_page = Input::get('initial_page');

$rules = [
    'initial_page' => 'required_with:end_page|integer|min:1|digits_between: 1,5',
    'end_page' => 'required_with:initial_page|integer|min:'. ($init_page+1) .'|digits_between:1,5'
]; 
查看更多
登录 后发表回答