Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel form input integer length

In Laravel form input validation, you can specify a minimum and a maximum length of a given input field.

$inputRules = [
    'postCode' => 'min:3|max:8'
];

Validation outcome

  • 'BA45TZ' = true
  • 'FF' = false
  • 'GH22 55XYZ' = false

However if I do the same for a number, it will validate whether the input is less than or greater than the input, then return on that.

$inputRules = [
    'cv2' => 'min:3|max:4'
];

Validation outcome

  • '586' = false
  • '4' = true
  • '2' = false
  • '3' = true

I actually want to validate a numbers length not it's numerical value. I can't figure out how to do this. Google has been no help, or I am not searching the right thing.

Anybody had any experience with this?

EDIT: I have answered my own question. I had missed Laravels digits_between.

like image 649
Alex McCabe Avatar asked Feb 18 '15 14:02

Alex McCabe


2 Answers

Like an idiot, I missed Laravels digits_between validator rule. I swear I had scoured those rules, but here we are.

Thank you everyone for your help.

$inputRules = [
    'cv2' => 'required|numeric|digits_between:3,4'
];
like image 180
Alex McCabe Avatar answered Sep 30 '22 16:09

Alex McCabe


That's the expected behavior of Laravel's size, min and max validations. You can't change it.

For string data, value corresponds to the number of characters. For numeric data, value corresponds to a given integer value. For files, size corresponds to the file size in kilobytes.

To solve this you have to create a custom validation rule. Something like this:

Validator::extend('min_length', function($attribute, $value, $parameters){
    return strlen($value) >= $parameters[0];
});

Validator::extend('max_length', function($attribute, $value, $parameters){
    return strlen($value) <= $parameters[0];
});

And you can use them in the same way:

'cv2' => 'min_length:3|max_length:4'
like image 42
lukasgeiter Avatar answered Sep 30 '22 18:09

lukasgeiter