Laravel 5.2 - validation rule does not work

Asked

Viewed 465 times

1

I need to do a validation of a zip code field, but the following attempts do not work:

$rules= ['cep'  => 'required|numeric|size:8'];
ou
$rules= ['cep'  => 'required|numeric|min:8'];
ou
$rules= ['cep'  => 'numeric|size:8'];

The following validations function:

$rules= ['cep'  => 'required|numeric'];
ou
$rules= ['cep'  => 'required|size:8'];

Does anyone have any idea why it doesn’t work?

1 answer

3


ZIP CODE can begin with 0, example 01415000, then you can’t have numeric and the size:8 together and will never have eight numbers if you start with 0.

So the ideal for validation would be with digits:8: this validation works by checking if all are numbers and if the number quantity is equal to 8 inclusive the 0.

$rules = ['cep'  => 'required|digits:8'];

If you want to create a validation with your own code follow the example below:

Registering a validation:

Validator::extend('cep', function($attribute, $value, $parameters, $validator) {
    return mb_strlen($value) === 8 && preg_match('/^(\d){8}$/', $value)
});

$rules= ['cep'  => 'required|cep'];

In this aspect will work the validation in its way. In this link, are the validations that the Laravel has for version 5.2 and 5.3 so far.

  • Thanks for the reply, @Virgilio-novic ! But, regardless of the ZIP code validation case, if I do the same validation of a field that, for example, should be filled, numerical and have 3 digits, the $Rules= ['campox' => 'required|Numeric|size:3'] rule still doesn’t work.

  • 1

    @Julioalves I did the editing and now do the test with digits:8, because in these digits it needs to be a number with an exact amount of numbers, including the 0 to the left.

  • 1

    Now yes, @Virgilionovic! Solved the problem. Thank you very much!

  • 1

    @Julioalves nice that was solved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.