Vaadin 浮点数字段(来自字符串字段验证)



我试图从字符串字段在Vaadin中创建一个浮点字段(我不知道任何其他方法;)

有一个验证,它应该允许我字符串字段只是一个浮点字段。我只找到了整数的解决方案?如何确保我的用户只能键入浮点数?

@Override
public void setConfiguration(EditorConfiguration editorConfiguration) {
    Validator<String> validator = ((FloatFieldConfiguration) editorConfiguration).getValidator();
    if (validator != null) {
        binder.forField(this).withValidator(validator)
                .withConverter(new StringToFloatConverter("Must enter a number"))
                .bind(s -> getValue(), (b, v) -> setValue(v));
    }
}

有多种方法可以实现您的目的,但我建议您通过实现Converter接口来使用自定义转换器。

您可以尝试以下操作:

class CustomConverter implements Converter<String, Double> {
  @Override
  public Result<Double> convertToModel(String fieldValue, ValueContext context) {
// Produces a converted value or an error
try {
  // ok is a static helper method that creates a Result
  return Result.ok(Double.valueOf(fieldValue));
} catch (NumberFormatException e) {
  // error is a static helper method that creates a Result
  return Result.error("Please enter a decimal value");
  }
}
  //for business object
 @Override
  public String convertToPresentation(Double dbl, ValueContext context) 
    {
// Converting to the field type should always succeed,
// so there is no support for returning an error Result.
return String.valueOf(dbl);
 }
}

之后,您只需在withConverter()方法中调用CustomConverter即可。(如.withConverter(new CustomConverter()).bind())。这是定义转化的理想方式(如果您想要完全按照自己的意愿。

希望它能满足您的目的..:)

相关内容

最新更新