Created
October 8, 2014 15:47
-
-
Save scottashipp/aa9b606a367e3b08609e to your computer and use it in GitHub Desktop.
Builder example, part 8, the ValidatorBuilder
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ValidatorBuilder { | |
private Validator v; | |
public ValidatorBuilder() { | |
v = new Validator(); | |
} | |
public Validator build() { | |
return v; | |
} | |
public Validator buildAndValidate() { | |
v.validate(); | |
return v; | |
} | |
public ValidatorBuilder withBlankFieldValidation(String... args) { | |
ValidationRule blankFieldRule = new ValidationRule() { | |
@Override | |
public String getErrorMessage() { | |
return "Required field is missing, null, or blank."; | |
} | |
@Override | |
public boolean validate(String arg) { | |
return (arg != null && !arg.isEmpty()); | |
} | |
}; | |
v.addValidationRule(blankFieldRule, args); | |
return this; | |
} | |
public ValidatorBuilder withEmailValidation(String... args) { | |
ValidationRule emailRule = new ValidationRule() { | |
@Override | |
public String getErrorMessage() { | |
return "Invalid email address. Please supply an email in the correct format."; | |
} | |
@Override | |
public boolean validate(String arg) { | |
return EmailValidator.getInstance().isValid(arg); | |
} | |
}; | |
v.addValidationRule(emailRule, args); | |
return this; | |
} | |
public ValidatorBuilder withBirthDateValidation(String... args) { | |
ValidationRule birthDateRule = new ValidationRule() { | |
@Override | |
public String getErrorMessage() { | |
return "Invalid birthday. Birthday must be in the format YYYY-MM-DD and in the past."; | |
} | |
@Override | |
public boolean validate(String arg) { | |
final String DATE_FORMAT = "yyyy-MM-dd"; | |
final SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT, Locale.FRANCE); | |
try { | |
Date now = new Date(); | |
Date birthday = sdf.parse(arg); | |
if(birthday.after(now)) { | |
return false; | |
} | |
} | |
catch (ParseException e) { | |
return false; | |
} | |
return true; | |
} | |
}; | |
v.addValidationRule(birthDateRule, args); | |
return this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment