mercoledì 10 novembre 2010

Custom Hibernate Validator Codice Fiscale

Some sample code to create an hibernate custom validator for Codice Fiscale:

CodiceFiscaleValidatorImpl.java
import java.lang.annotation.Annotation;
import org.hibernate.validator.Validator;
import org.jboss.seam.annotations.Name;

/**
 * @author Riccardo Merolla
 */
@Name("codiceFiscaleValidator")
public class CodiceFiscaleValidatorImpl implements Validator
{

 @Override
 public void initialize(Annotation arg0)
 {
  // TODO Auto-generated method stub
 }

 @Override
 public boolean isValid(Object arg0)
 {
  return ControllaCF((String) arg0);
 }

 public boolean ControllaCF(String cf)
 {
  int i, s, c;
  String cf2;
  int setdisp[] =
  {
    1,0,5,7,9,13,15,17,19,21,2,4,18,20,
    11,3,6,8,12,14,16,10,22,25,24,23
  };
  if (cf.length() == 0)
   return true;
  if (cf.length() != 16)
   return false;
  cf2 = cf.toUpperCase();
  for (i = 0; i < 16; i++)
  {
   c = cf2.charAt(i);
   if ( !(c >= '0' && c <= '9' || c >= 'A' && c <= 'Z'))
    return false;
  }
  s = 0;
  for (i = 1; i <= 13; i += 2)
  {
   c = cf2.charAt(i);
   if (c >= '0' && c <= '9')
    s = s + c - '0';
   else
    s = s + c - 'A';
  }
  for (i = 0; i <= 14; i += 2)
  {
   c = cf2.charAt(i);
   if (c >= '0' && c <= '9')
    c = c - '0' + 'A';
   s = s + setdisp[c - 'A'];
  }
  if (s % 26 + 'A' != cf2.charAt(15))
   return false;
  return true;
 }

}

CodiceFiscaleValidator.java
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.hibernate.validator.ValidatorClass;

/**
 * @author Riccardo Merolla
 */
@ValidatorClass(CodiceFiscaleValidatorImpl.class)
@Target({ElementType.FIELD, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface CodiceFiscaleValidator
{
 String message() default "{validator.assertFalse}";
}


Now you can add the annotation on your entity class like this:

@Column(name = "cod_fisc", length = 16
@Length(max = 16, message = "#{msg.error_stringlenght}")
@CodiceFiscaleValidator
public String getCodFisc()
{
   return this.codFisc;
}