Java-validation

@Valid
用于验证注解是否符合要求,直接加在变量之前,在变量中添加验证信息的要求,当不符合要求时就会在方法中返回message 的错误提示信息。

pom :

<dependency>
			<groupId>javax.validation</groupId>
			<artifactId>validation-api</artifactId>
			<scope>compile</scope>
</dependency>

entity :

@NotNull(message = "唯一标识ID不能为空")
@NotEmpty(message = "操作人姓名不能为空")

@Data
@NoArgsConstructor
@AllArgsConstructor
@SuperBuilder
@ApiModel(value="BaseOrgBscInfoUpdateOperVo",description="xxxxx请求参数")
@SuppressWarnings("serial")
public class XxxxVo implements Serializable {
	
	@ApiModelProperty(value = "唯一标识ID",required = true,example = "10")
	@NotNull(message = "唯一标识ID不能为空")
	private Long id;
	
	@ApiModelProperty(value = "操作人姓名",required = true,example = "李四")
	@NotEmpty(message = "操作人姓名不能为空")
	@Size(max=20,message="操作联系人姓名不能超过20个字符")
	private String handleName;
}

controller :

    @Valid
    
    @ApiOperation(tags = TAGS,value = "接口名称",notes="接口描述",position = 1,response = String.class)
    @PatchMapping(value = "/v1/xxx")
    public Object modifyOper(@ApiParam(required=true)  @Valid @RequestBody XxxxVo vo) {
	    return "SUCCESS";
    }

自定义validation :

ValidIdCard : 

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;
@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidIdCardImpl.class)
public @interface ValidIdCard {
	String message();
	Class<?>[] groups() default {};
	Class<? extends Payload>[] payload() default {};
}

ValidIdCardImpl : 

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import cn.hutool.core.util.IdcardUtil;
public class ValidIdCardImpl implements ConstraintValidator<ValidIdCard, Object> {
	@Override
	public boolean isValid(Object value, ConstraintValidatorContext context) {
	    // 进行验证操作并返回验证结果
		return IdcardUtil.isValidCard(String.valueOf(value));
	}
}

entity : 
使用 : @ValidIdCard(message="操作人身份证号无效")
@ApiModelProperty(value = "操作人身份证号",required = true,example = "321023198812214247")
@NotEmpty(message = "操作人身份证号不能为空")
@ValidIdCard(message="操作人身份证号无效")
private String handleSn;

原生支持的限制有如下几种:

限制 说明
@Null 限制只能为null
@NotNull 限制必须不为null
@AssertFalse 限制必须为false
@AssertTrue 限制必须为true
@DecimalMax(value) 限制必须为一个不大于指定值的数字
@DecimalMin(value) 限制必须为一个不小于指定值的数字
@Digits(integer,fraction) 限制必须为一个小数,且整数部分的位数不能超过integer,小数部分的位数不能超过fraction
@Future 限制必须是一个将来的日期
@Max(value) 限制必须为一个不大于指定值的数字
@Min(value) 限制必须为一个不小于指定值的数字
@Past 限制必须是一个过去的日期
@Pattern(value 限制必须符合指定的正则表达式
@Size(max,min) 限制字符长度必须在min到max之间
@Email 验证注解的元素值是Email,也可以通过正则表达式和flag指定自定义的email格式

validation 分组校验 :

通过group来实现,不做具体说明
参考 : https://blog.csdn.net/qq_33144861/article/details/77895366
发布了67 篇原创文章 · 获赞 10 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/qq_17522211/article/details/94381535
今日推荐