package nl.quintor.commons.util; import java.util.Calendar; /** * Validation class with various algorithms including validation for email addresses and postal codes. * * @author Benny Bottema */ public final class ValidatorUtils { /** * Regular expression used to validate postal code. * * @see #validatePostcode(String) */ private static final String REGEX_VALIDATION_POSTALCODE = "[1-9]{1}[0-9]{3}[a-zA-Z]{2}"; /** * Private constructor; This class is not meant to be instantiated. This is a utility class with static methods * only. */ private ValidatorUtils() { // } /** * Validates a dutch postal code using the following rules: *
null if validation succeeded.
* @see #REGEX_VALIDATION_POSTALCODE
* @see GenericUtils#regexPatternMatches(String, String)
*/
public static String validatePostcode(final String postalcode) {
if (postalcode == null) {
return ValidatorMessages.VALIDATIONERROR_POSTALCODE_UNAVAILABLE;
} else if (!GenericUtils.regexPatternMatches(REGEX_VALIDATION_POSTALCODE, postalcode)) {
return ValidatorMessages.VALIDATIONERROR_POSTALCODE_INVALID;
} else {
return null;
}
}
/**
* Validates an age (birth date) based on a specified minimum and maximum age. null if validation succeeded.
* @see Calendar
*/
public static String validateAge(final Calendar birthdate, final Integer min, final Integer max) {
if (birthdate == null) {
return ValidatorMessages.VALIDATIONERROR_BIRTHDATE_UNAVAILABLE;
} else if (birthdate.after(Calendar.getInstance())) {
return ValidatorMessages.VALIDATIONERROR_BIRTHDATE_INFUTURE;
} else {
final Calendar calendarMaxYearsAgo = Calendar.getInstance();
calendarMaxYearsAgo.roll(Calendar.YEAR, -max.intValue());
if (birthdate.before(calendarMaxYearsAgo)) {
return ValidatorMessages.VALIDATIONERROR_BIRTHDATE_TOOOLD;
} else {
final Calendar calendarMinYearsAgo = Calendar.getInstance();
calendarMinYearsAgo.roll(Calendar.YEAR, -min.intValue());
if (birthdate.after(calendarMinYearsAgo)) {
return ValidatorMessages.VALIDATIONERROR_BIRTHDATE_TOOYOUNG;
} else {
return null;
}
}
}
}
}