3

I have a simple POJO which is considered valid if one of the 2 attributes (ssn / clientId) is populated. I have written a custom Spring Validator to do the validation.

The question I have is, is there a way I can annotate my POJO so that my custom Validator is invoked for validation automatically? I'm trying to avoid manually invoking it from multiple places.

public class QueryCriteria {
    @NotNull
    private QueryBy queryBy;
    private String ssn;
    private String clientId;
}

public class QueryCriteriaValidator implements org.springframework.validation.Validator {
    @Override
    public boolean supports(Class<?> clazz) {
        return QueryCriteria.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        QueryCriteria criteria = (QueryCriteria) target;

        switch (criteria.getQueryBy()){
            case CLIENT:
                //validation logic
                break;

            case SSN:
                //validation logic
                break;

            default:
                break;
        }
    }
}

2 Answers 2

3

With Spring MVC, just add the custom validator to your controller's data binder:

@Autowired
private QueryCriteriaValidator validator;

@InitBinder
public void initializeBinder(WebDataBinder binder) {
    binder.addValidators(validator);
}

Otherwise, you'll want to inject the custom validator and call it yourself.

@Autowired
private QueryCriteriaValidator validator;

public void process(QueryCriteria criteria) {
    check(validator.validate(criteria));
    // Continue processing.
}
Sign up to request clarification or add additional context in comments.

2 Comments

I'm afraid, my application is not a web project and I don't use Spring MVC. This is a simple standalone service which needs to validate requests before consumption.
I believe the correct usage is to just inject it and call it. I updated my answer.
0

Só you can create your own validation. Example :

@RequiredParam
@RegexpValidation("^[\\p{IsLatin}]{2}[\\p{IsLatin}-]* [\\p{IsLatin}]{2}[\\p{IsLatin}- ]*$")
private String name;

Create a class validator e send the form that you want to validate:

Map<String, String> invalidFieldMap = Validator.validate(form);

    if (invalidFieldMap.size() > 0)
    { 
    LOGGER.warn("Invalid parameters");
    }

Look this gist Validator.java https://gist.github.com/cmsandiga/cb7ab4d537ef4d4691f7

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.