CodeValueValidator.java
/*
* Copyright 2026 Global Crop Diversity Trust
* Licensed under the Apache License, Version 2.0
* See LICENSE file in project root folder or http://www.apache.org/licenses/LICENSE-2.0
*/
package org.gringlobal.custom.validation.javax;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.gringlobal.component.elastic.AppContextHelper;
/**
* @author Maxym Borodenko
*/
public class CodeValueValidator implements ConstraintValidator<CodeValueField, String> {
/**
* Specified group.
*/
private String groupName;
/**
* When not strict then validation is skipped.
*/
private boolean strict;
/**
* Initializes the validator.
*/
@Override
public void initialize(CodeValueField constraintAnnotation) {
this.groupName = constraintAnnotation.value();
this.strict = constraintAnnotation.strict();
}
/**
* Implements the validation logic.
* @return {@code false} if {@code value} isn't defined in the specified group
*/
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null || !strict) {
return true; // nothing to validate here
}
if (! AppContextHelper.validateCodeValue(groupName, value)) {
context.disableDefaultConstraintViolation();
String message = value + " is not a valid CodeValue of " + groupName;
context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
return false;
}
return true;
}
}