package org.gwtoolbox.widget.client.form.validation.validator;
import com.google.gwt.i18n.client.DateTimeFormat;
import org.gwtoolbox.widget.client.form.validation.ValidationMessages;
import org.gwtoolbox.widget.client.form.validation.ValidationResult;
import org.gwtoolbox.widget.client.form.validation.Validator;
/**
* <p>Validates string according to the format as provided by the constructor. Valid strings are as mentioned by the
* javadoc from {@see com.google.gwt.i18n.client.DateTimeFormat}. A few examples are:</p>
* <ul>
* <li>dd-MM-yyyy</li>
* <li>dd-MMM-yy</li>
* </ul>
* <p/>
* <p>By providing a property validation.datestringformat you can influence the message returned in case of an error.
* The default is formatted like this</p>
* <pre>
* The valid format for the date is {0}
* </pre>
*
* @author Jettro Coenradie
*/
public class DateStringValidator implements Validator<String> {
private DateTimeFormat formatter;
private String format;
/**
* Constructor to accept a date format string
*
* @param format specified by the javadoc of {@see com.google.gwt.i18n.client.DateTimeFormat}
*/
public DateStringValidator(String format) {
this.format = format;
this.formatter = DateTimeFormat.getFormat(format);
}
/**
* Validates the provided string according to the format as provided through the constructor
*
* @param value T the value to be validated
* @return the result of the validation request
*/
public ValidationResult validate(String value) {
if (value != null) {
try {
formatter.parseStrict(value);
} catch (IllegalArgumentException e) {
return new ValidationResult(ValidationMessages.Instance.get().datestring(format));
}
}
return new ValidationResult();
}
}