Home>

I want to make my own validation with a web application in spring boot and check the input value

Error message

Custom validation method not called (results in any value without error)

Error message
Applicable source code

It's a Form
@Data
@ValiUserId
@ValiPassword
public class NewUserForm {

private String userId;

private String userName;

private String nwPassword;

private String ckPassword;

※ Omitted below
}
Controller
@RequestMapping (value ="ckNewUser")
public String ckNewUser (Model model, @ModelAttribute ("newUserForm") @ValiUserId NewUserForm form, BindingResult result,
@ModelAttribute ("sBean") SessionBean sBean) {
System.out.println (form.getUserId ());
System.out.println (form.getNwPassword ());
if (result.hasGlobalErrors ()) {
model.addAttribute ("newUserForm" ;, form);
return"newUserRegistration" ;;
}
return"successRegistration" ;;
}
* Since there is no validation check, "successRegistration" is always called.
Validation related

@Target ({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention (RetentionPolicy.RUNTIME)
@Constraint (validatedBy = UserIDValidator.class)
@Documented
public @interface ValiUserId {

String message () default"The entered USER ID is already registered" ;;// Error message
Class<?>[] groups () default {};// Declares the type to use for the argument
Class< ;? extends Payload>[] payload () default {};// Payload

}

public class UserIDValidator implements ConstraintValidator<ValiUserId, NewUserForm>{

private ValiUserId valiUserId;

@Autowired
private LoginService loginService;

@Override
public void initialize (ValiUserId annotation) {
// TODO auto-generated method stub
this.valiUserId = annotation;
}

@Override
public boolean isValid (NewUserForm value, ConstraintValidatorContext context) {
// TODO auto-generated method stub
System.out.println ("AAA");
return loginService.ckUserId (value.getUserId ());
}

Tried

I confirmed that the input value was correctly sent from html to Controller.

Supplemental information (FW/tool version etc.)

I am sorry that the source code is difficult to read.

  • Answer # 1

    The validation annotation used elsewhere also works for some reason
    * @ Valid added

    @RequestMapping (value ="ckNewUser")
    public String ckNewUser (Model model, @ModelAttribute ("newUserForm") @ValiPassword @ValiUserId @Valid NewUserForm form, BindingResult result,
    @ModelAttribute ("sBean") SessionBean sBean) {
    System.out.println (form.getUserId ());
    System.out.println (form.getNwPassword ());
    if (result.hasGlobalErrors ()) {
    return"newUserRegistration" ;;
    }
    return"successRegistration" ;;
    }