Created
July 14, 2018 20:47
-
-
Save nfrankel/dec5768d2d0ca9e776ca5b105de679dd to your computer and use it in GitHub Desktop.
Validating an email field with Vaadin 10
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
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