Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
How can we use either of the validation in spring boot?

I have two variables in my bean and I want either name or mobile to be filled, they cant be both null at the same time.

@NotNull
private String name;

@NotNull
private String mobile;

How can I achieve that?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

You need to write a custom annotation for this and use on class

@AtLeastOneNotEmpty(fields = {"name", "phone"})
public class User{

Custom Annotation Implementation

@Constraint(validatedBy = AtLeastOneNotEmptyValidator.class)
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface AtLeastOneNotEmpty {

  String message() default "At least one cannot be null";

  String[] fields();

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

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

And Validator of Custom Annotation

public class AtLeastOneNotEmptyValidator
    implements ConstraintValidator<AtLeastOneNotEmpty, Object> {

  private String[] fields;

  public void initialize(AtLeastOneNotEmpty constraintAnnotation) {
    this.fields = constraintAnnotation.fields();
  }

  public boolean isValid(Object value, ConstraintValidatorContext context) {

    List<String> fieldValues = new ArrayList<String>();

    for (String field : fields) {
      Object propertyValue = new BeanWrapperImpl(value).getPropertyValue(field);
      if (ObjectUtils.isEmpty(propertyValue)) {
        fieldValues.add(null);
      } else {
        fieldValues.add(propertyValue.toString());
      }
    }
    return fieldValues.stream().anyMatch(fieldValue -> fieldValue!= null);
  }
}
over 4 years ago · Santiago Trujillo Relatório

0

you can create your own validation or annotation try like this :

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNullConfirmed {
    String message() default "they can not be null";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

and class that implement it:

   public class FieldConfirmedValidator implements ConstraintValidator<NotNullConfirmed, Object>{
    @Override
    public boolean isValid(Object user, ConstraintValidatorContext context) {
        String name = ((Your_bo)user).getName();
        String phone = ((Your_bo)user).getPhone();
        return !name.isEmpty() && !phone.isEmpty();
    }
}

and add this annotation to your class

@NotNullConfirmed 
public class User{
}
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda