Reputation: 5628
I would like to use Hibernate Validator to validate arguments of my method.
I have tried to look-up examples and went through the following example JSR 303. Validate method parameter and throw exception
But the answer does not exactly solve my problem and also the links are expired in the answer.
Here is a sample code of what I have tried.
//removing imports to reduce the length of code.
/**
* Created by Nick on 15/06/2016.
*/
@Component
public class ValidationService {
@Value("${namesAllowed}")
private String validNames;
@Autowired
private Validator validator;
public boolean validateName(
@NotEmpty
@Pattern(regexp = ".*'.*'.*")
@Email
@Length(max = 10)
String name
) {
Set<ConstraintViolation<String>> violations = validator.validate(name);
for (ConstraintViolation<String> violation : violations) {
String propertyPath = violation.getPropertyPath().toString();
String message = violation.getMessage();
System.out.println("invalid value for: '" + propertyPath + "': " + message);
}
List<String> namesAllowed= Arrays.asList(validNames.split(","));
if (namesAllowed.contains(name.substring(name.indexOf(".") + 1))) {
return true;
}
return false;
}
}
}
Upvotes: 0
Views: 1969
Reputation: 19040
Method validation has been standardized as part of Bean Validation 1.1. You can learn more about it in the Hibernate Validator reference guide.
With Spring you need to configure a MethodValidationPostProcessor bean and annotate the constrained class with @Validated
. Also this answer may be helpful to you.
Upvotes: 1