0

I tried to create a float field in Vaadin from String field (I dont know any other method ;)

I have a validation which should allow me that a String field will be just a float field. I found only a solution for an integer? How to asure that my user can type only float number?

@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));
    }
}
Anna K
  • 1,666
  • 4
  • 23
  • 47

1 Answers1

2

There can be various ways to achieve your purpose but I would recommend you to use the custom converter by implementing the Converter Interface.

Here is something that you can try:

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);
 }
}

After that you can simply call CustomConverter inside the withConverter() method.(like .withConverter(new CustomConverter()).bind()). This is the ideal way to define your conversions(if you want something exactly as you wish.)

Hope it serves your purpose..:)