简体   繁体   中英

Which condition i need for laravel validation if i need to check max strlen just for numbers from a string which contains comma and dot

I have this situation:

An input which can contain max chars 11 ( eg 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,

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';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM