Home » Php » php – Laravel validation regex, breaks in view

php – Laravel validation regex, breaks in view

Posted by: admin July 12, 2020 Leave a comment

Questions:

So, I have the following rules in my model:

public static $rules = array(
    'name'            => 'required|alpha_dash|unique:subsidiaries',
    'internal_number' => 'required|alpha_dash|unique:subsidiaries',
    'expedition_rate' => array('required', 'regex:/^[0-9]{1,3}(\.?)[0-9]{1,2}$/'),
    'hundred_kg_rate' => array('regex:/^[0-9]{1,5}(\.?)[0-9]{1,2}$/'),
    'handling'        => array('regex:/^[0-9]{1,3}(\.?)[0-9]{1,2}$/'),
    'insurance'       => 'required|numeric',
);

But, for some reason, when the regex is applied in the pattern attribute tag in html… it breaks!

Result:

<input required="true" pattern="^[0-9]{" class="form-control" ....>
                               _________
                                 \
                                  => This right here should be
                               ^[0-9]{1,3}(\.?)[0-9]{1,2}$
How to&Answers:

Try using like this.

array(
    'field' => 'regex:[a-z]'
);

Hope this would helpful.

Answer:

Try escaping the curly braces… I bet PHP is expecting to parse a variable inside, like this:

$var = 'something';
echo 'The value is {$var}.';
// Outputs:
// The value is something.

Contrast this with:

$var = 'something';
echo 'The value is \{$var\}.';
// Outputs:
// The value is $var.

The part that confuses me though, is that these are within single quotes, and so this shouldn’t happen. Maybe a Laravel thing?