Dronax
Dronax

Reputation: 289

Laravel validation digits

I have a rule:

'price' => 'required|numeric|digits:8,13'

I need allow only 8 digits or 13 digits on validation. My code is not working. If I write 8 digits, then validation say that I need write 13 digits. How I can fix it?

Upvotes: 0

Views: 2759

Answers (3)

nice_dev
nice_dev

Reputation: 17805

Well, you can have a regex rule to mimic 8 digits or 13 digits.

'price' => array(
             'required',
             'numeric',
             'regex:/^(\d{8}|\d{13})$/',
           )

Upvotes: 3

namelivia
namelivia

Reputation: 2735

You need a custom validation rule. The pass function would be:

public function passes($attribute, $value)
{
    $digits = strlen((string)$value);
    return $digits === 8 || $digits === 13;
}

Upvotes: 0

Poldo
Poldo

Reputation: 1932

You can create custom validation for your need. Check laravel documentation here. https://laravel.com/docs/5.8/validation

Validator::extend('custom_rule_name',function($attribute, $value, $parameters){
  return  $value == 13 || $value == 8;
});

Upvotes: 1

Related Questions