I am trying to implement custom validation in spring boot but there is some issue with the code even if I am passing wrong phone number the phone number should be 10 digit but I am passing a string and still I get status as OK can anyone tell me what is wrong with my code
@Data
public class StudentData {
@Phone
String phone;
}
@RestController
public class HomeController {
@PostMapping("/showData")
public String display(@Valid @RequestBody StudentData studentData){
return "OK";
}
}
@Documented
@Constraint(validatedBy = PhoneValidation.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String message() default "{Wrong phone}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
public class PhoneValidation implements ConstraintValidator<Phone, String> {
@Override
public void initialize(Phone phone) { }
@Override
public boolean isValid(String phoneField, ConstraintValidatorContext constraintValidatorContext) {
if(phoneField == null) {
return false;
}
if(phoneField.matches("^[0-9]*$"))
return true;
return false;
}
}
Payload I am passing http://localhost:8080/showData { "phone":"abc" }