Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form Validation with Google Web Toolkit?

Tags:

validation

gwt

I'm new to GWT. What good solutions exist for form validation? I'd like to avoid rolling my own if possible.

like image 917
Nick Heiner Avatar asked May 28 '11 19:05

Nick Heiner


1 Answers

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

Sample validation error

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.

like image 192
DonX Avatar answered Nov 02 '22 04:11

DonX