Created
March 7, 2017 15:32
-
-
Save elmot/d382d2e58af95ce2d7e34e9f53d0a879 to your computer and use it in GitHub Desktop.
Vaadin 8:
Locale-specific validation message example.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.vaadin.tests; | |
import com.vaadin.data.Binder; | |
import com.vaadin.data.ErrorMessageProvider; | |
import com.vaadin.data.HasValue; | |
import com.vaadin.data.ValueContext; | |
import com.vaadin.data.converter.StringToIntegerConverter; | |
import com.vaadin.server.VaadinRequest; | |
import com.vaadin.tests.data.bean.Person; | |
import com.vaadin.ui.Button; | |
import com.vaadin.ui.Label; | |
import com.vaadin.ui.TextField; | |
import com.vaadin.ui.UI; | |
import com.vaadin.ui.VerticalLayout; | |
import java.util.Locale; | |
/** | |
* Created by elmot on 3/7/2017. | |
*/ | |
public class LocalizationExample extends UI { | |
@Override | |
protected void init(VaadinRequest request) { | |
TextField ageField = new TextField("Age"); | |
Binder<Person> binder = new Binder<>(Person.class); | |
binder.forField(ageField) | |
.withConverter(new StringToIntegerConverter("Not a number")) | |
// also might be done with RangeValidator, with overridden getMessage() | |
.withValidator(age -> (age >= 7) && (age <= 130), | |
new MyErrorMessageProvider(ageField)) | |
.bind(Person::getAge,Person::setAge); | |
setContent(new VerticalLayout(ageField,new Button("Validate", event->binder.validate()))); | |
setLocale(Locale.GERMANY); | |
} | |
private static class MyErrorMessageProvider implements ErrorMessageProvider { | |
private final HasValue<?> ageField; | |
public MyErrorMessageProvider(HasValue<?> ageField) { | |
this.ageField = ageField; | |
} | |
@Override | |
public String apply(ValueContext context) { | |
Locale locale = context.getLocale().orElse(Locale.US); | |
if (Locale.GERMAN.getLanguage().equals(locale.getLanguage())) { | |
return String.format(Locale.GERMAN, "Der Wert %s ist ung\u00fcltig. Bitte geben Sie eine Zahl zwischen 7 und 130 ein!", ageField.getValue()); | |
} else { | |
return String.format(Locale.ENGLISH, "Value %s is invalid, please enter a number from 7 to 130!", ageField.getValue()); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment