Julie
Julie

Reputation: 583

How to fix the size of field to maxlength using form_widget

I am using form_widget to render my field , what I want is to limit the digits to 5 (not to let the person type more then 8 digits ) somthing like maxlengh in html

I have tried :

 {{ form_widget(form.telMobile, {'attr':{'class': 'form-control','placeholder' :'number - 8 digits',  'size' : '8' }}) }}

 {{ form_widget(form.telMobile, {'attr':{'class': 'form-control','placeholder' :'number - 8 digits',  'maxlength' : '8'  }}) }}

How could I limit the number of digits before validation?

update:still not working

this is my form builder

->add('telMobile', null,array('label' => 'common.label.telmobile', 'required' => true ,'attr' => ['pattern' => '/^[0-9]{8}$/']))

and I have tried also to add the pattern to the widget :

 {{ form_widget(form.telMobile, {'attr':{'class': 'form-control','placeholder' :'Téléphone mobile - 8 chiffres', pattern' : '/^[0-9]{8}$/' }}) }}

as you see in the picture I still can type more than 8 digits

enter image description here

Upvotes: 1

Views: 14021

Answers (2)

msg
msg

Reputation: 8171

Since you are passing null to the FormBuilder as your field type, Symfony's Type Guessing System is kicking in. This tries to guess the appropiate form control for your field based on its definition. Judging by the arrows in the screenshot, it's resolving to NumberType, and a numeric field doesn't have a maxlength property.

To fix this, you'll have to explicitly set it to TextType:

->add('telMobile', TextType::class, array(
    'label' => 'common.label.telmobile', 'required' => true, 
    'attr' => ['pattern' => '/^[0-9]{8}$/', 'maxlength' => 8])
 )

This will, however, come with its own tradeoffs: now the input will be limited in length but the user will be able to input letters. If this is not desireable and you want to reject invalid input, you'll have to use a javascript solution.

Upvotes: 5

Andrew Vakhniuk
Andrew Vakhniuk

Reputation: 594

This question is related more to html options of number input, you can use 'max' and 'min' parameters in input of type number

<input type="number" min="1" max="99999" />

so using form_widget it will look next:

 {{ form_widget(form.number, {'attr':{'class': 'form-control','placeholder' :'number - 5 digits','type':'number',  'max' : '99999'  }}) }}

But more comfy will be to create form field using NumberType::class and add 'attr' there. Also if you need exactly 5 numbers , you can validate it using regex expression, but input type should be "text" then:

'pattern' : '[0-9]{5}'  -this will expect exactly 5 digits

To sum up, if you need it to be safe then better is to use regex on back-end side in symfony using validators. P.S. maxlength works if the input's type is text.

Upvotes: 0

Related Questions