Home > Blockchain >  Custom Validation Not Working on spring boot
Custom Validation Not Working on spring boot

Time:05-05

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" }

CodePudding user response:

Try adding @Validated to your controller.

If that does not work, I would also confirm that validation code is being hit. Running your API in debug mode with a breakpoint in the isValid method can confirm if this is a problem in the validation logic, the Bean validator injection or your test setup (is it a test scenario?).

CodePudding user response:

First, you don't need to use @Validated over @RestController, servlet container will validate it for you on data input annotated with @Valid Second, your regex validates all strings consisting of digits, in spite of their length, so "1" or "22222222222222222" is a valid Phone And last but not least - your code is working as desired :)

  • Related