diff --git a/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialValueBox.java b/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialValueBox.java index 5f83c3773..559a9e18d 100644 --- a/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialValueBox.java +++ b/gwt-material/src/main/java/gwt/material/design/client/ui/MaterialValueBox.java @@ -69,6 +69,11 @@ public class MaterialValueBox extends AbstractValueWidget implements HasCh HasDirectionEstimator, HasText, AutoDirectionHandler.Target, IsEditor>, HasIcon, HasInputType, HasPlaceholder, HasCounter, HasReadOnly, HasActive { + /** + * @see #setReturnBlankAsNull(boolean) + */ + private boolean returnBlankAsNull; + private InputType type = InputType.TEXT; private ValueBoxEditor editor; private Label label = new Label(); @@ -211,9 +216,41 @@ public void setType(InputType type) { @Override public T getValue() { + if(isReturnBlankAsNull() && isBlank()) { + return null; + } return valueBoxBase.getValue(); } + /** + * @see #setReturnBlankAsNull(boolean) + * + * @return + */ + public boolean isReturnBlankAsNull() { + return this.returnBlankAsNull; + } + + /** + *

With this attribute set to true a call to {@link #getValue()} returns null when + * the validator obtained by {@link #createBlankValidator()} recognizes the value as blank. + *

+ *

+ * You can use this attribute for non-mandatory input fields that have @Pattern constraint, like an e-mail or phone input. + * This way you avoid the @Pattern#regexp being matched against an empty string when your user does not enter + * a value into such input. + *

+ * + * @param returnBlankAsNull should {@link #getValue()} return null instead of a blank value? + */ + public void setReturnBlankAsNull(boolean returnBlankAsNull) { + this.returnBlankAsNull = returnBlankAsNull; + } + + protected boolean isBlank() { + return !createBlankValidator().isValid(valueBoxBase.getValue()); + } + @Override public void setValue(T value, boolean fireEvents) { valueBoxBase.setValue(value, fireEvents);