Cannot use Converter in Binding

Hello everyone,

I have problems using a converter for a binding.

Usecase: I got some Numberfields. Now I want to check whether the user entered letters instead of numbers so that my binding doesn’t cause an error.

This is the binder I wrote: (based on the StringToInteger converter in the vaadin documentation)

public class StringToDoubleConverter 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 nfe) {
		// error is a static helper method that creates a result
		return Result.error("Bitte geben Sie eine gültige Zahl ein.");
	}
}

@Override
public String convertToPresentation(Double doubleValue, ValueContext context) {
    // Converting to the field type should always succeed,
    // so there is no support for returning an error Result.
    return String.valueOf(doubleValue);
}

}

This is where I use the binder:

    binder.setBean(entry);
    binder.bindInstanceFields(this);

    binder.forField(dbPulse).withStatusLabel(statusLabelPulse).withNullRepresentation(0d);

    StringToDoubleConverter convStrToDblConverter = new StringToDoubleConverter();
    binder.forField(dbPulse).withConverter(convStrToDblConverter);

This is the error I get and I don’t understand it because it says that my parameter for the withConverter method has the wrong type, which is just not true:

The method withConverter(Converter<Double,NEWTARGET>) in the type Binder.BindingBuilder<MedicalJournalEntry,Double> is not applicable for the    arguments (StringToDoubleConverter)

Thanks for any help in advance! :slight_smile:

So I can answer this myself now, maybe someone else encounters this misconception.

The converter I implemented is not working for a NumberField because the NumberField is of type double. That is why my STRING to double converter is not working.

The only way of validating whether a user entered a number and not some rubbish which cannot be converted to a double value is to add @NotNull annotation to the bean property, because every user input in a numberfield that cannot be converted to a double value becomes null.

The problem with this is: you cannot divide between an empty number field and wrong input (e.g. entering letters into a numberfield), which means that you have the same error messages for both cases.

I don’t think that this is a good design decision. (especially when you use bean validation, I don’t know whether this problem also exists when using built-in vaadin validation)