Requirement - validate input as alpha numeric. I have two class are in Has-A relation
Quick help appreciate, thanks in advance.
public class Party {
@InputContraint
private String firstName;
@InputContraint
private String lastName;
private Address address;
}
public class Address {
@InputContraint
private String countryCode;
@InputContraint
private String countryName;
}
@Documented
@Constraint(validatedBy = InputValidate.class)
@Target( { ElementType.METHOD, ElementType.FIELD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface InputContraint {
String message() default "error.message";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class InputValidate implements ConstraintValidator<InputContraint, String> {
@Override
public boolean isValid(String inputVal, ConstraintValidatorContext context) {
if (Utilities.isEmpty(inputVal))
return true;
//
String regex = "^[a-zA-Z0-9]+$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(inputVal);
boolean valid = matcher.matches();
return valid;
}
}
Another way - still not working.
---
public class Address {
@Pattern(regexp ="^[a-zA-Z0-9]+$")
private String countryCode;
}
I have created custom annotation and applied at field level
- if field as
String
, it's working fine. - if filed as
Class
, is not working.
- if field as
Applied
@Pattern(regex="^[a-zA-Z0-9]+$")
atAddress.countryCode