, ( ):
-, TextInputCell , keypress, keypress , , -. KeyPressableTextInputCell. . , : TextInputCell.onBrowserEvent() GWT?
MaskedTextInputCell, onBrowserEvent() , . , 0-9 . . , ValidationStrategy MaskedTextInputCell.
public class MaskedTextInputCell extends KeyPressableTextInputCell {
public interface ValidationStrategy {
public boolean matches(String valueToCheck);
}
private ValidationStrategy overallFormValidationStrategy;
private ValidationStrategy validKeystrokeValidationStrategy;
public MaskedTextInputCell(ValidationStrategy overallFormValidationStrategy,
ValidationStrategy validKeystrokeValidationStrategy) {
this.overallFormValidationStrategy = overallFormValidationStrategy;
this.validKeystrokeValidationStrategy = validKeystrokeValidationStrategy;
}
@Override
public void onBrowserEvent(Element parent, String value, Object key, NativeEvent event,
ValueUpdater<String> valueUpdater) {
super.onBrowserEvent(parent, value, key, event, valueUpdater);
if ("keypress".equals(event.getType())) {
String keystroke = String.valueOf((char) event.getCharCode());
handleInvalidKeystroke(keystroke, event);
} else if ("blur".equals(event.getType()) || "keyup".equals(event.getType())) {
String valueInInputElement = getInputElement(parent).getValue();
handleInvalidOverallForm(valueInInputElement);
}
}
protected void handleInvalidOverallForm(String valueOfEntireField) {
if (!overallFormValidationStrategy.matches(valueOfEntireField)) {
GWT.log("Invalid form.");
}
}
protected void handleInvalidKeystroke(String keystroke, NativeEvent event) {
if (!validKeystrokeValidationStrategy.matches(keystroke)) {
GWT.log("Invalid keystroke.");
event.preventDefault();
}
}
}
ValidationStrategy :
public class RegularExpressionValidationStrategy implements MaskedTextInputCell.ValidationStrategy {
private String regularExpression;
public RegularExpressionValidationStrategy(String regularExpression) {
this.regularExpression = regularExpression;
}
@Override
public boolean matches(String valueToCheck) {
return valueToCheck.matches(regularExpression);
}
}
- , :
public class MonetaryTextInputCell extends MaskedTextInputCell {
public MonetaryTextInputCell() {
super(new RegularExpressionValidationStrategy("[0-9.]"),
new RegularExpressionValidationStrategy("^[0-9.][0-9]*[0-9.]?[0-9]*$"));
}
}