实现List<Sting>的正则表达式验证

java

浏览数:461

2019-1-12

片段 1片段 2


自定义实现ListPattern注解

@Service
public class ListPatternImpl implements ConstraintValidator<ListPattern, List> {
    
    private String regexp;
    
    @Override
    public void initialize(ListPattern constraintAnnotation) {
        this.regexp = constraintAnnotation.regexp();
    }
    
    public boolean isValid(List list, ConstraintValidatorContext constraintValidatorContext) {
        if (this.regexp == null || StringUtils.isBlank(this.regexp))
            return true;
        if (list == null || list.size() <= 0)
            return true;
        Pattern pattern = Pattern.compile(this.regexp);
        return list.stream().filter(rule -> rule == null || !pattern.matcher(rule.toString()).find()).count() == 0;
    }
}


在实体类中使用@ListPattern的方式进行注解,然后在web层使用@volid即可进行验证

public class testDTO {
    @ListPattern(regexp = "ip地址", message = "请输入正确的IP地址")
    private List<String> ips;
}