Hibernate ScriptAssert for arrays validation

让人想犯罪 __ 提交于 2021-02-11 14:40:51

问题


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<>();
}

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

Please help. Thanks.


回答1:


Edit:

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;
  }
}

Test:

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);
  }
}


来源:https://stackoverflow.com/questions/58859352/hibernate-scriptassert-for-arrays-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!