Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bean validation for Integer field

I am trying to have constraint validation on the field, which must reject if the input is not an integer.

public class ClientTO {
       private Integer phone_num; //
}

I tried:

1) @Digits - It does not validate if input is integer or not as you could see the type mismatch exception is still thrown.

2) My custom validation - which seems to not work on Integer fields

Error:

Exception in thread "main" javax.validation.UnexpectedTypeException: HV000030: No validator could be found for type: java.lang.Integer.

My custom validation class:

public class X_CVAImpl implements ConstraintValidator<X_CustomValidatorAnnotation,String>{  
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // TODO Auto-generated method stub
        boolean val_d;
        if (value.matches("[0-9]+") && value.length() ==10) {
            val_d=true;
        }else {
            val_d=false;            
        }
        return val_d;
    }
}

Any help please?

like image 833
sql_dummy Avatar asked Nov 15 '18 14:11

sql_dummy


People also ask

What does @NotNull annotation mean in bean property?

The @NotNull annotation is, actually, an explicit contract declaring that: A method should not return null. Variables (fields, local variables, and parameters) cannot hold a null value.

What is the use of @valid annotation?

The @Valid annotation ensures the validation of the whole object. Importantly, it performs the validation of the whole object graph. However, this creates issues for scenarios needing only partial validation. On the other hand, we can use @Validated for group validation, including the above partial validation.


1 Answers

@Digits will only work for primitive types. So if you change your entity to the following, your validation should kick in.

public class ClientTO {
   @Digits(integer=10, fraction=0)
   private int phone_num; // Constraint: phone_num can only be 10 digits long or less
   ...
}

Having that said, I believe that you should use a string to validate a phone number.

public class ClientTO {
   @Size(min=10, max=10)
   @Pattern(regexp="(^[0-9]{10})")
   private String phone_num; // Constraint: phone_num would match 10 digits number
   ...
}
like image 171
dirbacke Avatar answered Sep 22 '22 14:09

dirbacke