I am using a Vaadin text field and I want to restrict it to support numbers only in it. I tried to override setValue()
and return without calling super. setValue()
if text is not a number. But it doesn't seems to be working. How can I correct this?
I am using Vaadin 7. And I think it doesn't support NumberField as well.
If I understand you question correct, you want to have a field that ignores all inputs that are not a number and not only mark the field as invalid. Vaadins architecture is designed that every field in the browser has its representation on the server. In my opinion the cleanest way to achieve this would be to have a browser field, that permits input of letters and other wrong characters. I couldn't find such a field in Vaadin 7. There seems to be an add-on for vaadin 6 called Number Field for that, but I didn't test it.
You have multiple options:
Port this add-on to vaadin 7 or ask the author to do it
Write your own field. Maybe extending VTextField and TextFieldConnector
Do everything on the server side and accept the delays and the traffic (IMHO ugly)
Since I think option 3 is not the way to go, I probably shouldn't show this code, but it's the quickest way to implement this.
public class IntegerField extends TextField implements TextChangeListener {
String lastValue;
public IntegerField() {
setImmediate(true);
setTextChangeEventMode(TextChangeEventMode.EAGER);
addTextChangeListener(this);
}
@Override
public void textChange(TextChangeEvent event) {
String text = event.getText();
try {
new Integer(text);
lastValue = text;
} catch (NumberFormatException e) {
setValue(lastValue);
}
}
}