Bean Validation Custom Constraint – Java

In order to create a custom constraint for a bean validator, first you should declare an interface and decorate it with the following annotations:

@Target = what it works on

@Retention = must be runtime in order to work on runtime

@Constraint = the custom validator (if you have created one)

@Documented = if provided will document the constraint on the java docs.

In the example below there is a custom validator for a URL address that returns error when the protocol or the host are not correct or well formed.

@Target({ METHOD, ANNOTATION_TYPE ,FIELD, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Constraint(validatedBy = {URLValidation.class})
@Documented 
 
 public @interface URL{  
   String message() default "malformed URL"; 
   Class<?>[] groups() default { };  
   Class<? extends Payload>[] payload() default { };

String protocol() default="";
 
 }

Then Create the custom Validation noted in the @Constraint annotation:

public class URLValidator implement ConstraintValidator<Url,String> {  
  String protocol;
 
  @Override
  public void initialize(URL url){
    this.protocol = url.protocol();
   }

  @Override   public boolean isValid(String object, ConstraintValidatorContext cons traintContext) {

java.net.URL url;
try {
  url = new java.net.URL(object)
}
catch(MalformedUrlException e){ return false;}

if ( protocol != null && protocol.length()>0 && !url.getProtocol().equals(protocol)) {return false;}

return true;
}

Create any class (it doesn’t have to be a bean class although my example is) and annotate it with the URL custom validation on a field

package beans;
imoprt java.io.* 

public class ServerConnection implements Serializable 
{   
  @URL(protocol="https") 
  private String baseURL;
  public ServerConnection() {}
  public ServerConnection (String baseUrl) {
      this.baseURL = baseURL;
    }

  public getBaseURL {
    return this.baseUrl;
  }
}

Now to see how it works just create Validation Factory and a connection in the class Main or where ever you use it:

ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
javax.validation.Validator validator = factory.getValidator();
Set<ConstraintViolation<ServerConnection>> violation;

ServerConnection connection = new ServerConnection("https://www.google.com");

violations =validator.validate(connection);
if(violations.size()>0){

// do failback logic

}

 

Comments are closed, but trackbacks and pingbacks are open.