Home > Enterprise >  Which condition i need for laravel validation if i need to check max strlen just for numbers from a
Which condition i need for laravel validation if i need to check max strlen just for numbers from a

Time:12-03

I have this situation:

An input which can contain max chars 11 ( e.g. 12345678.00 ) 10 numbers and 1 comma or dot. I need to check only if max strlen of numbers is grater than 10, for example user cannot insert this number 12345678901. This input is for price.

So, i use laravel framework and in my function at the beggining i already extracted the max strlen value of numbers of that input but i don't know how to put in laravel condition.

My function:

$price = (int) filter_var($request->price, FILTER_SANITIZE_NUMBER_INT);
$max = strlen($price);
$this->validate($request, 
//rules for input validation
[
  'price' => ??
],

//message for input validation
[
  'price.??'  => 'Some text error'
]);

If exist another way to verify the condition in php and send the message please tell me. For clarifying i cannot use numeric number, or max|min condition..

Best regards,

CodePudding user response:

You have to create a custom validator. For that you can follow this blog. How to Create Custom Validation Rules Laravel

So your custom validator will look like this namespace App\Rules;

use Illuminate\Contracts\Validation\Rule;

class StrDigitCalculator implements Rule
{

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $int = (int) filter_var($value, FILTER_SANITIZE_NUMBER_INT);
        return strlen($int) == 10 : true : false;
        
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        // Your custom message for this validation
        return 'Validation Fails';
    }
}
  • Related