Yeasir Arafat
Yeasir Arafat

Reputation: 2191

Laravel validation rule for mathematical expression

I want to take mathematical input from users and save them in database. Then, I want to show the result of the mathematical expression. Now, I need a validation rule to check if the input is a valid mathematical expression. It need not to be very complex. Just basic addition and subtraction is enough for me. For example, 2+4+5+8 or 5-2+4. I do not even need any bracket. Can anyone give me a validation rule that works for laravel validator?

Upvotes: 0

Views: 495

Answers (1)

bjovanov
bjovanov

Reputation: 481

I would create a specific validation rule for this because I don't think Laravel includes it by default. So let's make a php artisan make:rule Expression and inside of it, something like that:

public function passes($attribute, $value)
{
    $value = preg_replace('\s', '', $value);
    return preg_match("/^\d+([\+\-\*\/]{1}\d+)+$/", $value);
}

As you can see, I have previously removed any form of white space because it makes regex simpler while accepting cases such as: "2+5", "2 + 5", "2+ 5', "2 + 5".

Then you can just call it in your Controller like:

'input' => ['required', new Expression]

To manage brackets, unfortunately regex won't help you. You'll have to use a kind of parser able to handle the infinite possibility of grouping expressions such as "2 + (5 * (3 / (1/2)))"). * 5)".

Upvotes: 1

Related Questions