On a Symfony project I’m working on, I have two phone (one mobile) text input fields on a form that I would prefer to display to the user with the format “(888) 555-1000”, but yet allow the user to just input numbers. I accomplished this with Javascript, and this blog describes how I did it.

Symfony Form

In my controller as part of my “createFormBuilder” I added the following TextType built-in Field Type code:

->add('phone', TextType::class, array(
      'label' => 'Phone #:',
      'attr' => array(
            'placeholder' => '(xxx) xxx-xxxx',
            'size' => 13,

What this looks like in HTML is like so:  phonefield

Which displays how the format would look after fully entering the number. The way I wanted it to work, is the user clicks on the field, it automatically adds the first bracket, and then as then continuously enter in digits, the closing bracket / space / and dash are added.

Using JSFiddle to Experiment

Javascript is a terrible language to work with. It is easy to make mistakes, and there is very little feedback to tell you what might be wrong. So often you have to use the browser debugging tools to figure out why your script doesn’t work. Which is what I had to do for this particular script.

Fortunately you can use as a tool to create your html, css, and Javascript to fully test out your Javascript in a test environment to see if it works before deploying. Although, if you are new to JSFiddle, you will need to get familiar with it.

Here is a link to my public sample of this code:

Twig Code

In order to call each of the Javascript functions, I had to add attributes to my Twig code for the form rending of my TextType widgets. I also set the maximum length so that when the user enters more than 14 digits, nothing will happen (this is good).

Here is a sample of my Twig code:

{{ form_label( }}
    {{ form_widget(,{'attr':{
    }}) }}


Using Modern Javascript

I saw some online posts using KeyboardEvent.charCode, but that is deprecated and it is recommend to us KeyboardEvent.key instead. It’s surprising how much bad code you can find out there that works but really is not current at all.

And example of using the event to get this code would be like this:

if (e.key !== "Backspace") {

Where “Backspace” is a Key value. There are a lot of Key values, so this can be very useful when making your code (reduces errors).

Hope this helps!