So I have some problems with phone number validation.
This happens, when I try to put something what is not a number. I need to prevent this.
I have already tried many ways, but in some reason nothing work. Can you tell me where is my mistake?
What am I tried before in model(Entity):
#[ORM\Column(nullable: true)]
1) // #[Assert\Regex('/^\(0\)[0-9]*$')]
or 2) // #[Assert\Type(
// type: 'integer',
// message: 'The value {{ value }} is not a valid {{ type }}.',
// )]
private ?int $phone = null;
Also I tried this in my Form:
->add('phone', TelType::class,[
'required' => false,
'constraints' => [
new Regex([
'pattern' => '/^\+?[0-9]{10,14}$/',
'message' => 'Please enter a valid phone number',
])
],
])
Validator is imported, regex also, for name and email validation work fine. Problem only with the phone number.
What wrong with my code?
Thank you in advance!
It's your typehinting on your $phone
property that's causing the error, just like @craigh and @Dylan KAS mention. TelType
returns a string
, as it's an input element of type tel
, see here.
By typehinting ?int
, PHP expects the provided value to either be null or an integer. Assuming you are trying invalid phonenumbers like 'abcd' or '124578785758583', Symfony will throw an error as that those are strings.
I'd recommend to replace your typehinting with ?string
and make sure your regex is correct and you check for type "numeric", which uses the is_numeric function:
#[ORM\Column(nullable: true)]
#[Assert\Regex('/^\(0\)[0-9]*$')]
#[Assert\Type(
type: 'numeric',
message: 'The value {{ value }} is not a valid {{ type }}.',
)]
private ?string $phone = null;