Springboot使用Hibernate Validator实现多参数必填其一等自定义校验

Springboot使用Hibernate Validator实现多参数必填其一等自定义校验

实现多参数必填其一校验

项目中有遇到多参数必填其一校验,百度无果后查看Hibernate Validator官方文档1解决了问题。

场景

通过手机号和身份证作为uniqueId来查询到唯一的用户,作为一个类的两个属性,在controller层使用@Validted注解进行参数校验。

解决方式

百度了基本都是@NotBlank等注解加在类的属性上,暂时没有发现好的能校验必填其一的方法。
所以写自定义方法实现,后发现在方法上加@NotBlank/@AssertTrue等注解无效。
查询了官方文档,发现关键在于自定义的方法需要getter。
文档如下图:
在这里插入图片描述
所以@NotBlank加在自定义方法上无效的原因是方法没有以get开头

代码实现

类中:

@Data
public class UserParam {

    /**
     * 用户手机号
     */
    @ApiModelProperty(value = "用户手机号")
    private String mobile;

    /**
     * 用户身份证号
     */
    @ApiModelProperty(value = "用户身份证号")
    @JsonProperty(value = "id_card")
    private String idCard;
    
	/**
     * 校验mobile和idCard必填其一
     */
    @AssertTrue(message = "手机号和身份证号必填其一")
    public Boolean getUserValid(){
        return !StrUtil.isAllBlank(this.mobile, this.idCard);
    }
}

controller层参数注解:

@PostMapping("/xxx")
@ApiOperation(value = "xxx接口", notes = "xxx接口")
public Response xxx(@Validated @RequestBody UserParam param)

  1. Hibernate Validator官方文档 ↩︎

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值