
In gwt based application most of the time we are having same validation for text boxes. Below is my favorite style I use it for my gwt applications. It is a small abstraction over validation logic. So that validator's functionality can be tested using unit test cases easily. Same thing can be used for other input boxes also like PasswordBox.
CustomTextBox.java
public class CustomTextBox extends TextBox {
private static final String TEXTBOX_VALIDATION_ERROR_STYLE = "error-text-box";
private String errorMessage = "";
private List
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;
}
}
Style to be included in .css file
.error-text-box {
border: 1px solid red;
background: white url("../images/icons/validation_error_icon.gif") no-repeat left center;
padding-left: 15px !important;
}
Error Icon :
You can change this as per your taste

Final Validation display looks like below
