I'm new to GWT. What good solutions exist for form validation? I'd like to avoid rolling my own if possible.
In my GWT applications I always use my custom validator classes. I have created my own textbox class which extends gwt textbox. And I call CustomTextBox instead of gwt's textbox.
CustomTextBox.java
public class CustomTextBox extends TextBox implements HasValidators{
private static final String TEXTBOX_VALIDATION_ERROR_STYLE = "error-text-box";
private String errorMessage = "";
private List<Validator> validators = new ArrayList<Validator>();
public CustomTextBox() {
}
public CustomTextBox(String name) {
setName(name);
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public void addValidator(Validator validator) {
validators.add(validator);
}
public boolean validate() {
boolean validationResult = true;
for (Validator validator : validators) {
validationResult = validator.validate(getValue().trim());
if (!validationResult) {
errorMessage = validator.getErrorMessage();
break;
}
errorMessage = validator.getErrorMessage();
}
setErrorStyles(validationResult);
return validationResult;
}
private void setErrorStyles(boolean validationResult) {
if (validationResult) {
removeStyleName(TEXTBOX_VALIDATION_ERROR_STYLE);
setTitle("");
} else {
addStyleName(TEXTBOX_VALIDATION_ERROR_STYLE);
setTitle(errorMessage);
}
}
@Override
public void setValue(String s) {
removeStyleDependentName(TEXTBOX_VALIDATION_ERROR_STYLE);
super.setValue(s);
}
@Override
public String getValue() {
return super.getValue().trim();
}
}
Validator.java
public abstract class Validator {
public String errorMessage;
public abstract boolean validate(String value);
public abstract String getErrorMessage();
}
Sample Email validator
public class EmailValidator extends Validator {
public boolean validate(String value) {
if (value.matches("^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}$")) {
errorMessage = "";
return true;
} else {
errorMessage = "Enter valid email Id";
return false;
}
}
public String getErrorMessage() {
return errorMessage;
}
}
My validation error looks like following
If you like this approach you can follow this. The problem here is we don't display the error message directly in the UI. Only in tooltip we are showing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With