简体   繁体   中英

Create a validation method which throw MethodArgumentNotValidException

I'm trying to validate this class:

public class RegisterRequest {
    @Email(message = "format e-mail non valide") @NotNull(message = "ne doit pas être vide")
    private String email;
    @NotEmpty(message = "ne doit pas être vide")
    @NotBlank(message = "ne doit pas être vide")
    @NotNull(message = "ne doit pas être vide")
    private String prenom;
    @NotEmpty(message = "ne doit pas être vide")
    @NotBlank(message = "ne doit pas être vide")
    @NotNull(message = "ne doit pas être vide")
    private String nom;
    @Length(min = 13,max = 13 ,message = "doit contenir exactement 13 chiffres")
    @NotNull(message = "ne doit pas être vide")
    @Pattern(regexp = "^\\d*$", message = "ne doit contenir que des chiffres")
    @Pattern(regexp = "^[12]\\w*$", message = "doit commencer par 1 ou 2")
    private String cin;
    @NotNull(message = "ne doit pas être vide")
    @Pattern(regexp = "^(?!.*  .*)[\\d+() ]{9,20}$", message = "ne doit contenir que des chiffres , des parentheses et plus")
    @Length(min = 9,max = 20)
    private String telephone;
    @NotNull(message = "ne doit pas être vide")
    @Length(min = 5,max = 20,message = "la taille de caractère doit être entre 5 et 20")
    @Pattern(regexp = "^(?=[a-zA-Z\\d._-]*$)(?!.*[_.]{2})[^_.].*[^_.]$",message = "ne doit contenir de caractère special  a part _ , .,-")
    private String login;
}

after construction with ObjectMapper like this:

@Slf4j
public class CustomValidator {
    ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
    Validator validator = factory.getValidator();
    public Boolean validate(Object object){
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        log.info(violations.toString());
        String errorMessage =
                violations.stream().map(ConstraintViolation::getMessage).collect(Collectors.joining(", "));
        throw new MethodArgumentNotValidException(errorMessage);
    }
}

as you see i can't use the @Valid annotation here (note: if there is a method to use the annotation directly i'll prefere it. but i didnt find any way to do it.
so i've found that it is better to create a validator class so after some research i've found this method

 MethodParameter parameter, BindingResult bindingResult

but it is not working take two argument in his constructor:
 MethodParameter parameter, BindingResult bindingResult

so my question is how create this argument and how to throw it like @Valid throw it or is there any other way to handle the validation error

So, i've found this solution but i'm not throwing MethodArgumentNotValidException anymore i've created my own exception class like this:

@Getter @Setter
public class ArgumentValidationExption extends Exception{
    private final Map<String, String> errors;
    public ArgumentValidationExption(Map<String,String> errors) {
        super();
        this.errors = errors;
    }

@ExceptionHandler(ArgumentValidationExption.class)
    public ResponseEntity<?> ArgumentInvalid(ArgumentValidationExption arg){
        return jsonResponse(false,arg.getErrors(),400,arg.getClass().getSimpleName());
    }

and in my validator class ill just throw my exception like this:

public void validate(Object object) throws ArgumentValidationExption {
        Set<ConstraintViolation<Object>> violations = validator.validate(object);
        if (violations.size() == 0 ) return ; 
        Map<String, String> errors = new HashMap<>();

        for (ConstraintViolation<Object> constraint: violations
             ) {
            errors.put(constraint.getPropertyPath().toString(), constraint.getMessageTemplate());
        }
        throw new ArgumentValidationExption(errors);
        
    }
}

if you found a better solution please let me know

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM