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


i have 2 fields optional 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 greater initial_page. how include filter?

there no built-in validation let compare field values in laravel, you'll need implement custom validator, let reuse validation needed. luckily, laravel makes writing custom validator really easy.

start 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 can use brand new validation rule in $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 creating custom validators here: http://laravel.com/docs/5.1/validation#custom-validation-rules. easy define , can used everywhere validate data.


Comments

Popular posts from this blog

php - Admin SDK -- get information about the group -

dns - How To Use Custom Nameserver On Free Cloudflare? -

Python Error - TypeError: input expected at most 1 arguments, got 3 -