package com.njcn.web.utils;


import cn.hutool.core.collection.CollectionUtil;

import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import java.util.Set;

/**
 * @author hongawen
 * @version 1.0.0
 * @date 2021年06月10日 14:10
 */
public class ValidatorUtils {

    /**
     * 校验所有字段并返回不合法字段
     */
    public static void validate(@Valid Object domain) {
        Set<ConstraintViolation<@Valid Object>> validateSet = Validation.buildDefaultValidatorFactory()
                .getValidator()
                .validate(domain, new Class[0]);
        if (!CollectionUtil.isEmpty(validateSet)) {
            String messages = validateSet.stream()
                    .map(ConstraintViolation::getMessage)
                    .reduce((m1, m2) -> m1 + "；" + m2)
                    .orElse("参数输入有误！");
            throw new IllegalArgumentException(messages);
        }
    }

}
