Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
429 views
in Technique[技术] by (71.8m points)

php - Laravel: validate an integer field that needs to be greater than another

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...