valida校验关联参数、指定属性值

一、自定义校验规则

import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * title:   商品属性校验
 *
 * @author: hetao
 * Date:     2020/1/9 16:29
 */
public class AttributeValidator implements Validator {

    @Override
    public boolean supports(Class aClass) {
        return AttributeInsertCommand.class.equals(aClass);
    }

    @Override
    public void validate(Object obj, Errors errors) {
        //把校验信息注册到Error的实现类里
        AttributeInsertCommand attribute = (AttributeInsertCommand) obj;
        AttributeInputEnum inputEnum = AttributeInputEnum.ELECTION;
        List attributeValue = attribute.getAttributeValue();
        List collect = attributeValue.stream().map(AttributeValue::getValue).filter(Objects::nonNull).collect(Collectors.toList());

        if (attribute.getAttrInputType() == inputEnum.getCode() && collect.size() == 0) {
            errors.rejectValue("attributeValue", null, "输入方式为" + inputEnum.getMsg() + "时,属性值必填");
        }
    }
}

二、请求实体

import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

import javax.validation.constraints.NotEmpty;
import java.io.Serializable;
import java.util.List;

/**
 * title:    商品属性新增
 * Date:     2019/12/31 13:31
 *
 * @author hetao
 */
@Data
@ApiModel("商品属性新增")
public class AttributeInsertCommand implements Serializable {

    private static final long serialVersionUID = -6273001214036704660L;

    /**
     * 属性名称
     */
    @ApiModelProperty("属性名称")
    @NotEmpty(message = "属性名称不能为空")
    private String attrName;

    /**
     * 状态, 1:启用   0:禁用
     */
    @ApiModelProperty("状态,1:启用,0:禁用")
    @EnumValue(intValues = {1, 0})
    private Integer status;

    /**
     * 属性输入类型 1:下拉框 2:文本
     */
    @ApiModelProperty("属性输入类型,1:下拉框 2:文本")
    @EnumValue(intValues = {1, 2})
    private Integer attrInputType;

    /**
     * 属性描述
     */
    @ApiModelProperty("属性值数组")
    private List attributeValue = Lists.newArrayList();

}

三、controller

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;

/**
 * Date:     2020/1/2 10:09
 * title:title
 *
 * @author hetao
 */
@RestController
@RequestMapping("/api/attribute")
@Api(value = "属性管理", tags = "属性管理")
public class AttributeController {

    @InitBinder
    public void initBinder(WebDataBinder webDataBinder) {
        webDataBinder.addValidators(new AttributeValidator());
    }

 /**
     * 商品属性新增
     *
     * @param attributeInsertCommand 商品属性新增
     * @return JsonResult
     */
    @PostMapping
    @ApiOperation("商品属性新增")
    public JsonResult addAttribute(@RequestBody @Valid AttributeInsertCommand attributeInsertCommand, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            JsonResult jsonResult = JsonResult.create(Integer.parseInt(ResultEnum.APP_VALIDATION_ERROR.getCode()), fieldError.getDefaultMessage(), false);
            return jsonResult;
        }
        return JsonResult.create(attributeService.addAttribute(attributeInsertCommand));
    }
}

三、自定义EnumValue注解

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * title:    校验指定值
 *
 * @author: hetao
 * Date:     2020/1/9 16:59
 */
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {EnumValueValidator.class})
public @interface EnumValue {

    //默认错误消息
    String message() default "必须为指定值";

    String[] strValues() default {};

    int[] intValues() default {};

    //分组
    Class[] groups() default {};

    //负载
    Class[] payload() default {};

    //指定多个时使用
    @Target({FIELD, METHOD, PARAMETER, ANNOTATION_TYPE})
    @Retention(RUNTIME)
    @Documented
    @interface List {
        EnumValue[] value();
    }
}

注解实现

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * title:   自定义枚举校验
 *
 * @author: hetao
 * Date:     2020/1/9 17:00
 */
public class EnumValueValidator implements ConstraintValidator {

    private String[] strValues;
    private int[] intValues;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (Integer s : intValues) {
                if (s == value) {
                    return true;
                }
            }
        }
        return false;
    }
}

你可能感兴趣的:(valida校验关联参数、指定属性值)