Last active
March 5, 2021 00:05
-
-
Save Omar-Salem/caf302cfc4bb7f45952d79a61338fc67 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.springframework.stereotype.Service; | |
import javax.validation.ConstraintViolation; | |
import javax.validation.Validation; | |
import javax.validation.Validator; | |
import javax.validation.ValidatorFactory; | |
import java.util.Collection; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
@Service | |
public class ModelValidator { | |
private final ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); | |
private final Validator validator = factory.getValidator(); | |
public <T> void validate(T model) { | |
Collection<ConstraintViolation<T>> violations = validator.validate(model); | |
if (violations.isEmpty()) { | |
return; | |
} | |
final List<String> errorMessages = violations | |
.stream() | |
.map(c -> c.getPropertyPath() + " " + c.getMessage()) | |
.collect(Collectors.toList()); | |
throw new ValidationException(errorMessages); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment