3

I am trying to make a regex for price OR empty. I have the price part (Dutch uses comma instead of point) which actualy works

/^\d+(,\d{1,2})?$/

The regex above validates ok on the value 21,99

Now I try to add the empty part so the field can be... just empty ^$

/(^$|^\d+(,\d{1,2})?$)/

But Laravel starts to complain as soon as I change the regex: "Method [validate^\d+(,\d{1,2})?$)/] does not exist."

Works ok:

$rules = [
    'price' => 'regex:/^\d+(,\d{1,2})?$/'
];

Laravel says no...:

$rules = [
    'price' => 'regex:/(^$|^\d+(,\d{1,2})?$)/'
];

Kenken9990 answer - Laravel doesn't break anymore but an empty value is still wrong:

$rules = [
    'price' => 'regex:/^(\d+(,\d{1,2})?)?$/'
];
poashoas
  • 1,790
  • 2
  • 21
  • 44
  • 1
    Can you add a valid & invalid patterns, from which regex need to validate. – Sinto Jul 02 '18 at 18:55
  • In php are you able to use a regex like a lambda function? I didn't think you could. – emsimpson92 Jul 02 '18 at 18:57
  • @emsimpson92 I am not a programmer, a Lambda? – poashoas Jul 02 '18 at 19:02
  • My apologies, I meant an anonymous function. `=>` is C# syntax for exactly that. It looks like it has [a different meaning](https://stackoverflow.com/questions/14037290/what-does-this-mean-in-php-or) in PHP. Your problem is with the `=>` – emsimpson92 Jul 02 '18 at 19:05
  • @emsimpson92 In PHP you create an array like that. Example 1 works, example 2 fails. It's just the regex I think, or Laravel..., oh and now I know what you mean with Lamba, something with passing a value to a function or something? – poashoas Jul 02 '18 at 19:08
  • Yes, but you're assigning a keyvaluepair with the key `price` and value `your regex`. the regex is not your value, just the pattern you want to run the value through – emsimpson92 Jul 02 '18 at 19:08

2 Answers2

9

is this work ?

$rules = [
    'price' => 'nullable|regex:/^(\d+(,\d{1,2})?)?$/'
];
poashoas
  • 1,790
  • 2
  • 21
  • 44
kenken9999
  • 765
  • 1
  • 6
  • 14
2

| is also the separator for multiple validation rules.

For example the following is valid:

 $rules = [ "price" => "nullable|numeric|between:0,99" ];

To use it regex you need to switch to using an array:

$rules = [
    'price' => [ 'regex:/(^$|^\d+(,\d{1,2})?$)/' ]
];

This is also pointed out in the documentation:

Note: When using the regex / not_regex patterns, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.

Incidentally the original rule might also do what you want and can also be written as:

$rules [
     'price' => [ 'nullable', 'numeric', 'between:0,99' ]
]
apokryfos
  • 38,771
  • 9
  • 70
  • 114