1

In Symfony 2, I have a name field that I want to validate. If it contains a number, I want to show a message. My code is:

//Entity/Product.php
 /**
     * @ORM\Column(name="`name`", type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\NotNull()
     * @Assert\Regex(pattern="/[0-9]/",match=false,message="Your name cannot contain a number")
     */
    protected $name;

But when I write a number in the field, I see this message:

Please match the requested format

because my field code is like below:

<input type="text" id="mzm_testbundle_category_name" name="mzm_testbundle_category[name]" required="required" maxlength="255" pattern="((?![0-9]).)*">

input tag has a pattern and error that i see is from HTML5. How can i resolsve this problem?

TylerH
  • 20,799
  • 66
  • 75
  • 101

1 Answers1

7

The message you see is not coming from the Symfony validator directly. The form framework defines HTML validation when possible, and the message is indeed coming from the client side validation.

Overriding the client side message

Constraint API's setCustomValidity() can be used to update the client side message.

You can either do it while defining a field:

$builder->add(
    'name',
    'text',
    [
        'attr' => [
            'oninvalid' => "setCustomValidity('Your name cannot contain a number')"
        ]
    ]
));

or in a twig template:

{{ form_row(
       form.name, 
       {
           'attr': {
               'oninvalid': "setCustomValidity('Your name cannot contain a number')"
           } 
       }
 ) }}

Disabling client side validation

You could also disable the HTML validation:

{{ form(form, {'attr': {'novalidate': 'novalidate'}}) }}

References

TylerH
  • 20,799
  • 66
  • 75
  • 101
Jakub Zalas
  • 35,761
  • 9
  • 93
  • 125
  • Great, also you need to add slashes if you have some languages with aphostrophes: `'oninvalid' => "setCustomValidity('".addslashes($options['translator']->trans('blabla'))."')"` – the_nuts Jun 17 '17 at 15:40