来自其他字段javax.validation的条件中的选项的字段验证 [英] Field validation from options on condition from other field javax.validation

查看:286
本文介绍了来自其他字段javax.validation的条件中的选项的字段验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果存在另一个字段,我需要执行一个字段验证(可以是值之一).

I need to perform a field validation (it can be one of values) if another field is present.

import javax.validation.*;

class Person {

    @NotBlank
    private String name;

    private Long groupId;

    @Valid // if group id is not null, select one from available.
    private String specialization;

    // getters, setters.
}

class PersonValidaionLogic {

    @Autowired
    private SpecializationService specializationService;

    public void validatePerson(final Person person) {
        Long groupId = person.getGroupId();
        if (groupId != null) {
            Set<String> availableSpecializations = specializationService.getByGroupId(groupId);
            if (!availableSpecializations.contains(specialization)) {
                addValidationError("specialization is not valid");
            }
        }
    }
}

对于如何验证一个字段中的多个字段,有一个很好的答案彼此有条件的班级.

There is a nice answer on how to validate multiple fields in a class with conditions on each other.

如何将specializationServicegroupId传递给验证器.

How do I pass specializationService and groupId to the validator.

推荐答案

随时分享您的解决方案或想法!这就是我解决这个问题的方式.

Feel free to share your solution or ideas! This is how I solved this problem.

我在问题中的链接中使用了这个主意,但方法要简单得多.

I used the idea from the link in my question, but in much easier way.

首先,我解决了一个问题如何将Spring组件或服务传递到验证器中.我使用了一个包含对该服务的静态引用的组件.

First, I solved a problem how to pass a Spring component or service into validator. I used a component which holds a static reference to the service.

第二,我按照链接中所述验证了整个对象.

Second, I validated the whole object as described in the link.

代码在这里!

1)创建注释@PersonConstraint并放入Person类. 这可能会帮助 https://www.baeldung.com/javax-validation-method-constraints

1) Create annotation @PersonConstraint and put in on Person class. This may help https://www.baeldung.com/javax-validation-method-constraints

@Target({ TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = PersonValidator.class)
public @interface PersonConstraint {

    String message() default "Specialization is not valid";

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };

    CaseMode value();
}

2)包含对服务的静态引用的组件.

2) Component which holds static reference to the service.

@Component // Spring component.
class ServiceHolderComponent {

    private static SpecializationService SPECIALIZATION_SERVICE;

    @Autowired
    public ServiceHolderComponent(final SpecializationService specializationService) {
        GROUP_SERVICE = Validate.notNull(groupService); //apache lib
    }

    public static SpecializationService getSpecializationService() {
        return SPECIALIZATION_SERVICE;
    }
}

3)和人员验证器

public class PersonValidator implements ConstraintValidator<PersonConstraint, Person> {

    private final SpecializationService specializationService;

    public UserDynamicEnumValidator() {
        this(ServiceHolderComponent.getSpecializationService());
    }

    public UserDynamicEnumValidator(final SpecializationService specializationService) {
        this.specializationService = specializationService;
    }

    @Override
    public boolean isValid(final Person person, final ConstraintValidatorContext context) {
        final Long groupId = person.getGroupId();
        if (groupId == null) {
            return true; // We consider it valid.
        }

        final String specialization = person.getSpecializat();
        if (StringUtils.isEmpty(specialization)) {
            return true; // We consider it valid.
        }

        // I changed the code of the service, so it returns a set of strings - projection query and collectors to set.
        final Set<String> availableSpecializationValuesByGroup = specializationService.findByValue(groupId);

        if (!availableSpecializationValuesByGroup.contains(specialization)) {
            // To display custom message
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("Specialization is not valid").addConstraintViolation();
            return false;
        }

        return true;
    }
}

显示验证器中的自定义消息选中此

这篇关于来自其他字段javax.validation的条件中的选项的字段验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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