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.
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);
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);
NumberFieldThird alternative is to use the NumberField component.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With