-2

I'm trying to validate a parameter structure that should match values like: 1200x800 , 1200x, x800 or simply x And so i'm using the following constraint:

'size' => [
                new Assert\NotBlank(),
                new Assert\Regex([
                    'pattern' => '/(\d+)?x(\d+)?/i'
                ])
            ],

The regex works fine as a standalone, but inside symfony constraint it also match cases like 1200x800x500. Im guessing behind the scene that it uses the preg_match_all? That would explain it since using: preg_match_all('/(\d+)?x(\d+)?/i', $data['size'], $size);, gives the following result:

array:3 [▼
  0 => array:2 [▼
    0 => "1500x800"
    1 => "x500"
  ]
  1 => array:2 [▼
    0 => "1500"
    1 => ""
  ]
  2 => array:2 [▼
    0 => "800"
    1 => "500"
  ]
]

Is there a way to make it stop at the first occurrence? Basically allow only: 1200x800 , 1200x, x800 or simply x

Petru Lebada
  • 2,087
  • 2
  • 29
  • 50

1 Answers1

2

You could set the ^ start-of-string and $ end-of-string anchors inside the regex:

/^(\d+)?x(\d+)?$/i
AymDev
  • 3,440
  • 2
  • 24
  • 42
boppy
  • 792
  • 8
  • 7