Reputation:
I have a form field that I want to check if the user submitted a correct pattern. I tried it this way.
// $car_plate should in XXX-1111, or XXX-111(three letters in uppercase followed by a dash and four or three numbers)
<?php
$car_plate = $values['car_plate'];
if (!preg_match('[A-Z]{3}-[0-9]{3|4}$', $car_plate)) {
$this->errors ="Pattern for plate number is XXX-1111 or XXX-111";
} else {
// code to submit
}
?>
The following car_plate numbers is in correct format (AAA-456, AGC-4567, WER-123). In this case it always return the error. What is the correct way?
Upvotes: 0
Views: 304
Reputation: 4035
alternative to TimoSta's answer.
/^[a-zA-Z]{3}-?\d{3,4}$/
this allows for user to enter letters in lowercase and to skip the dash
you can format the data later like this:
$input = 'abc1234';
if ( preg_match( '/^([a-zA-Z]{3})-?(\d{3,4})$/', $input, $matches ) )
{
$new_input = strtoupper( $matches[1] ) . '-' . $matches[2];
echo $new_input;
}
outputs: ABC-1234
Upvotes: 2
Reputation: 42460
Looks like you're a little bit off with your regular expression.
Try this one:
/^[A-Z]{3}-[0-9]{3,4}$/
In PHP, you have to enclose your regular expression with delimiters, in this case the slashes. In addition to that, {3|4}
is not valid, the correct syntax is {3,4}
as you can see in the docs covering repetition.
Upvotes: 1