Hibernate ScriptAssert用于数组验证 [英] Hibernate ScriptAssert for arrays validation

查看:72
本文介绍了Hibernate ScriptAssert用于数组验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Hibernate Script Assert进行条件验证:如果commRolesId包含4并且gnrlTransportersId数组列表为空,我想显示错误消息.

I am using Hibernate Script Assert to have a conditional validation: I want to have the error message shown if commRolesId contains 4 and gnrlTransportersId array list is empty.

@ScriptAssert(lang="javascript", script="this.commRolesId.indexOf(4) >= 0 && _this.gnrlTransportersId.length == 0", message="{notBlank.message}")
public class CommUserDto {
    @Size(min = 1, message = "{notBlank.message}")
    private List<Long> commRolesId = new ArrayList<>();

    private List<Long> gnrlTransportersId = new ArrayList<>();
}

但是,即使commRolesId数组不包含4,它也会抛出该消息.

But it is throwing the message even though commRolesId arrays does not contain 4.

请帮助.谢谢.

推荐答案

import java.util.ArrayList;
import java.util.List;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.ScriptAssert;

@ScriptAssert(
    lang = "javascript",
    script = "!(_this.commRolesId.contains(4) && _this.gnrlTransportersId.isEmpty())",
    message = "errorMessage")
public class CommUserDto {
  @Size(min = 1, message = "should not be empty")
  private List<Long> commRolesId = new ArrayList<>();

  private List<Long> gnrlTransportersId = new ArrayList<>();

  public List<Long> getCommRolesId() {
    return commRolesId;
  }

  public void setCommRolesId(List<Long> commRolesId) {
    this.commRolesId = commRolesId;
  }

  public List<Long> getGnrlTransportersId() {
    return gnrlTransportersId;
  }

  public void setGnrlTransportersId(List<Long> gnrlTransportersId) {
    this.gnrlTransportersId = gnrlTransportersId;
  }
}

测试:

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

public class Test {

  public static void main(String[] args) {
    CommUserDto dto = new CommUserDto();
    List<Long> commRolesId = new ArrayList<>();
    commRolesId.add(1L);
    List<Long> gnrlTransportersId = new ArrayList<>();
    dto.setGnrlTransportersId(gnrlTransportersId);
    dto.setCommRolesId(commRolesId);
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<CommUserDto>> constraintViolations = validator.validate(dto);
    System.out.println(constraintViolations.size());
    System.out.println(constraintViolations);
  }
}

这篇关于Hibernate ScriptAssert用于数组验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆