Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Construct vaadin 14 Textfield which accepts only numbers nothing else

Tags:

java

vaadin

I need to make the vaadin 14 textfield which can accept only numbers.The criterias for the textfield are as follows

1.The textfield must only accept numbers nothing else as I want to use that textfield as a mobile number field. 2.validate in such a way that if users tries to enter the alphabets nothing must be reflected in the textfield.Only numbers must be allowed to be entered in the textfield. 3.Any warning or errors must not be shown in the UI as we are specially making textfield for the mobile number.

Things I have tried is binders but that allows to enter the alphabets later on after the focus lost event they validate and provide the error message I dont want that behaviour.

Also tried vaadin number field but that allows character 'e'

Just simple and straight forward I am looking for the textfield which takes input only numbers.If user tries to input alphabets nothing must be reflected in the textfield.

like image 428
kushal Baldev Avatar asked Dec 10 '25 13:12

kushal Baldev


2 Answers

Server-side

There are number of options you can do, the first one is the server side validator already mentioned in the answer by Alim Özdemir:

binder.forField(textFieldForNumber)
      .withValidator(new RegexpValidator("Only 1-9 allowed","\\d*"))
      .bind(YourEntity::getNo, YourEntity::setNo);

Client-side

There is also possibility do the same checking and input filtering on client side using textField.setPattern(..) method, e.g.:

textFieldForNumber.setPattern("\\d*");

Furthermore it is possible to prevent input not matching the pattern alltogether by

textFieldForNumber.setPreventInvalidInput(true);

Alternate widget: NumberField

Third alternative is to use the NumberField component.

like image 144
Tatu Lund Avatar answered Dec 12 '25 03:12

Tatu Lund


You could do a validation on the field with the binder like

binder.forField(textFieldForNumber)
      .withValidator(new RegexpValidator("Only 1-9 allowed","\\d*"))
      .bind(YourEntity::getNo, YourEntity::setNo);
like image 27
Alim Özdemir Avatar answered Dec 12 '25 03:12

Alim Özdemir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!