Java Enumeration Type with validator
import java.util.HashMap; import java.util.Map; import java.util.regex.Pattern; enum FieldType {/*from w w w.j a v a2 s . c o m*/ PASSWORD("password") { @Override public boolean validate(String fieldValue) { return Pattern.matches("((?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{6,})", fieldValue); } }, EMAIL_ADDRESS("email") { @Override public boolean validate(String fieldValue) { return Pattern.matches("^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z|a-z]{2,4}$", fieldValue); } }, PHONE_NUMBER("phone") { @Override public boolean validate(String fieldValue) { return Pattern.matches("^1?[- ]?\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", fieldValue); } }, SOCIAL_SECURITY_NUMBER("ssn") { @Override public boolean validate(String fieldValue) { return Pattern.matches("^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$", fieldValue); } }; // End of enum constants definition // Instance members // private String fieldName; private FieldType(String fieldName) { this.fieldName = fieldName; } public String getFieldName() { return this.fieldName; } abstract boolean validate(String fieldValue); } public class Main{ // Static class members // private static final Map<String, FieldType> nameToFieldTypeMap = new HashMap<>(); static { for (FieldType field : FieldType.values()) { nameToFieldTypeMap.put(field.getFieldName(), field); } } public static FieldType lookup(String fieldName) { return nameToFieldTypeMap.get(fieldName.toLowerCase()); } private static void printValid(FieldType field, String fieldValue, boolean valid) { System.out.println(field.getFieldName() + "(\"" + fieldValue + "\") valid: " + valid); } public static void main(String... args) { String fieldName = "password"; String fieldValue = "123"; // invalid - must be at least 6 characters FieldType field = lookup(fieldName); printValid(field, fieldValue, field.validate(fieldValue)); fieldName = "phone"; fieldValue = "1-800-555-1234"; // valid field = lookup(fieldName); printValid(field, fieldValue, field.validate(fieldValue)); fieldName = "email"; fieldValue = "css@demo2s"; // invalid - missing .<tld> field = lookup(fieldName); printValid(field, fieldValue, field.validate(fieldValue)); fieldName = "ssn"; fieldValue = "111-11-1111"; // valid field = lookup(fieldName); printValid(field, fieldValue, field.validate(fieldValue)); } }