Home > OS >  Hibernate Validator custom constraint not working
Hibernate Validator custom constraint not working

Time:12-01

I am trying to create a custom contraint with Hibernate Validator. If I use a standard one such as @Size, it's work well and I got the error message. However, my custom one is not working and I cannot figure why.

This is my code:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ ElementType.FIELD, ElementType.PARAMETER })
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = TestValidateur.class)



public @interface ObjectValid {


    String message() default "test";
     
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
    
}

And:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;



public  class TestValidateur implements ConstraintValidator<ObjectValid , String>  {

      public void initialize(ObjectValid constraintAnnotation) {
        
      }

    public boolean isValid(String NoObject, ConstraintValidatorContext ctx) {

         return false ;
    
}

}

@Column(name="NoObject")
@ObjectValid
@Size(min = 4, max = 14)
public String NoObject;

And to test the validation:

import java.io.FileNotFoundException;
import java.util.Set;

import javax.persistence.EntityManager;

import org.hibernate.mapping.Component;
import org.hibernate.validator.HibernateValidator;


import jakarta.validation.ConstraintViolation;
import jakarta.validation.Validation;
import jakarta.validation.Validator;
import jakarta.validation.ValidatorFactory;



public class NoTest {
    private static Validator validator;

   public static void main(String[] args) throws FileNotFoundException, NoSuchMethodException, SecurityException {


       Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
       Object objectVerif = new Object("ss");
       Set<ConstraintViolation<Object>> validationErrors = validator.validate(objectVerif);
       if(!validationErrors.isEmpty()){
           for(ConstraintViolation<Object> error : validationErrors){
               System.out.println(error);

       }

       }  

}
}

If I run the app, I only receive the error message for the @Size

ConstraintViolationImpl{interpolatedMessage='la taille doit être comprise entre 4 et 14', propertyPath=NoObject, rootBeanClass=class tp03.Object, messageTemplate='{jakarta.validation.constraints.Size.message}'}

If anyone has a clue of what I a am missing, it would be really appreciated

thank you

Validated object:

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.*;

import org.hibernate.annotations.OnDelete;
import org.hibernate.annotations.OnDeleteAction;

import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Null;
import jakarta.validation.constraints.Size;

@Entity
@Table(name="object",indexes = { @Index(name="primary",columnList = "idObject")})

public class Object {

    
    
@Id
@GeneratedValue
@Column(name="idObject")    
private int idObject;

public int getidObject()
{
    {return idObject;}
}

public void SetidObject(int idObject)
{
    
    this.idObject=idObject;
}


@Column(name="NoObject")
@ObjectValid
@Size(min = 4, max = 14)
public String NoObject;


public String getNoObject()
{
    {return NoObject;}
}

public void SetNoObject(String NoObject)
{
    
    this.NoObject=NoObject;
}

public Object(String NoObject)
{this.NoObject=NoObject;
}


}

CodePudding user response:

The problem here is that the javax.validation.Constraint was used for defining the custom constraint, but the jakarta.validation.Validator is used for carrying out the validation, which then only validates jakarta.validation.Constraints.

If you change your imports from javax to jakarta in the ObjectValid constraint interface and the TestValidateur class, both constraints are validated correctly.

  • Related