4
votes
public function rules() {
        return [
            'num_of_devices' => 'integer'
        ];
}

I want to validate an integer field if and only if the field is entered. But above rule validates it for integer even if the field is empty. I used somtimes, but no result. But when I var_dump($num_of_devices) it is string.I am using Laravel 5.2. I think It was working fine in 5.1.

3

3 Answers

21
votes

From version 5.3 you can use nullable

public function rules() {
        return [
            'num_of_devices' => 'nullable | integer'
        ];
}
5
votes

Add a rule to array, if input is not empty. You could collect all your validation rules to $rules array and then return the array.

if( !empty(Input::get('num_of_devices')) ){
  $rules['num_of_devices'] = 'integer';
}
0
votes

You’re looking for the sometimes validation rule. From the documentation:

…run validation checks against a field only if that field is present in the input array.