Reputation: 37
class employee{
...
private long phone;
...
}
I want to validate phone number using spring jsr303 validator, In my Controller I am using @valid. I am successfully validating entered value is number or string by using generic typeMismatch placing in error message property file.
But I want to validate entered number format is correct or not.(@pattern for string only)
How to achieve this one,please suggest me.
Upvotes: 2
Views: 5510
Reputation: 1395
Normally phone numbers are String and you can validate by using @Pattern, but if you want to validate any fields you can do like this.
Custom annotation Javax validator
@javax.validation.Constraint(validatedBy = { PhoneNumberConstraintValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface ValidPhoneNumber {
}
public class PhoneNumberConstraintValidator implements ConstraintValidator<ValidPhoneNumber, Long> {
@Override
public void initialize(final ValidPhoneNumber constraintAnnotation) {
// nop
}
@Override
public boolean isValid(final Long value, final ConstraintValidatorContext context) {
//your custom validation logic
}
}
class employee{
...
private long phone;
@ValidPhoneNumber
public Long getPhone() { return phone; }
...
}
OR simpler if you have hibernate validator, you can just add this method in your entity class.
@org.hibernate.validator.AssertTrue
public boolean validatePhoneNumber() { }
Upvotes: 1