Laravel validation regex, breaks in view

11,413

Try using like this.

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

Hope this would helpful.

Share:
11,413
Alex
Author by

Alex

Why stop learning?

Updated on June 21, 2022

Comments

  • Alex
    Alex almost 2 years

    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}$
    
  • Alex
    Alex over 10 years
    How can one, escape curly braces in a regex syntax? This is new for me
  • Thomas Kelley
    Thomas Kelley over 10 years
    Double all of the backslashes.
  • Thomas Kelley
    Thomas Kelley over 10 years
    Sorry, I think I misunderstood your question. To escape the curly brace, you should just be able to do \{...\}. When it renders, it shouldn't have that backslash.
  • Alex
    Alex over 10 years
    I have tried it, with no positive effect. But the problem I don't think it's the backslash, since if I do {1\\,3} I'll eventually get a "^[0-9]{1" and no more
  • Thomas Kelley
    Thomas Kelley over 10 years
    That's weird. You may want to ask this question over at Laravel's GitHub... It might very well be a bug. I looked at their validation test cases, and none of them include curly braces: github.com/laravel/framework/blob/…
  • Alex
    Alex over 10 years
    Well, somebody replied my question in Laravel's forums... and it seems that it might be a bug: forums.laravel.io/viewtopic.php?pid=56239#p56239
  • Thomas Kelley
    Thomas Kelley over 10 years
    Interesting. In your case, rather than write a custom validator, you could instead just rewrite your RegEx to not include that comma. For example, x{1,3} can also be represented as xx?x?. At any rate, good luck with your project!