构造只接受数字的 vaadin 14 Textfield

kus*_*dev 3 java vaadin

我需要制作只能接受数字的 vaadin 14 文本框。文本框的标准如下

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.

Tat*_*und 6

服务器端

您可以执行多种选择,第一个是Alim Özdemir答案中已经提到的服务器端验证器:

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

客户端

也可以使用textField.setPattern(..)方法在客户端进行相同的检查和输入过滤,例如:

textFieldForNumber.setPattern("\\d*");
Run Code Online (Sandbox Code Playgroud)

此外,可以通过以下方式防止输入与模式完全不匹配

textFieldForNumber.setPreventInvalidInput(true);
Run Code Online (Sandbox Code Playgroud)

替代小部件: NumberField

第三种选择是使用NumberField组件。