Skip to content

Instantly share code, notes, and snippets.

@nfrankel
Created July 14, 2018 20:47
Show Gist options
  • Save nfrankel/dec5768d2d0ca9e776ca5b105de679dd to your computer and use it in GitHub Desktop.
Save nfrankel/dec5768d2d0ca9e776ca5b105de679dd to your computer and use it in GitHub Desktop.
Validating an email field with Vaadin 10
public class EmailField extends TextField implements HasValidator<String> {
public EmailField() {
super("Email");
addValueChangeListener(event -> {
String value = getValue();
if (value == null || value.trim().isEmpty()) {
resetToValid();
} else {
ValidationResult result = getDefaultValidator().apply(value, null);
if (result.isError()) {
setToInvalid(result.getErrorMessage());
} else {
resetToValid();
}
}
});
}
private void setToInvalid(String errorMessage) {
setInvalid(true);
setErrorMessage(errorMessage);
}
private void resetToValid() {
setInvalid(false);
setErrorMessage(null);
}
@Override
public Validator<String> getDefaultValidator() {
return new EmailValidator("Value " + getValue() + " is not an email");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment