I have a drop-down field called ContactTypeName that has values ββlike phone, email, etc., and an input field called Contact . I want to check the input field for a valid email address if the Email dropdown is selected ...
<h / "> I have the next bean
@FieldMatch.List({ @FieldMatch(first = "contactDetail", second = "contectTypeName", message = "Please Enter a valid email address") }) public class Contact { private int contactId = 0; @NotNull(message="Please Select a Contact Type") private Integer contectTypeId; private String contectTypeName; @NotNull(message="Please Specify Contact Details") private String contactDetail; }
im trying to create a custom constraint that will check the contactDetail field against an email regular expression if the ContactTypeName field is ContactTypeName to Email
I have the following code for user restriction
@Target({TYPE, ANNOTATION_TYPE,METHOD, FIELD}) @Retention(RUNTIME) @Constraint(validatedBy = FieldMatchValidator.class) @Documented public @interface FieldMatch { String message() default "{constraints.fieldmatch}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; String first(); String second(); @Target({TYPE, ANNOTATION_TYPE}) @Retention(RUNTIME) @Documented @interface List { FieldMatch[] value(); } }
and validator like
public class FieldMatchValidator implements ConstraintValidator<FieldMatch, Object> { private String firstFieldName; private String secondFieldName; private Pattern pattern; private Matcher matcher; private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@" + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; @Override public void initialize(final FieldMatch constraintAnnotation) { firstFieldName = constraintAnnotation.first(); secondFieldName = constraintAnnotation.second(); pattern = Pattern.compile(EMAIL_PATTERN); } @Override public boolean isValid(final Object value, final ConstraintValidatorContext context) { try { final Object firstObj = BeanUtils.getProperty(value, firstFieldName);
the problem is that it does not run the post ... im form using the Prime Faces model dialog where the bean check is performed
REF: Cross Field Validation with Hibernate Validator (JSR 303)
I look forward to your suggestions and recommendations