Sunday, September 13, 2015

Create a custom validation in Spring MVC4

There are few simple steps to create your custom validation :

1- Create a new package (ex. com.yourcompany.view)
2- Create a new annotation like in the screenshot below




3- Add the following annotation to your annotation interface as in the code below

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;


@Documented
@Constraint(validatedBy=PhoneConstraintValidator.class)
@Target({ElementType.METHOD,ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {

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


4- Define another class called PhoneConstraintValidator in the same package and the below code

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

public class PhoneConstraintValidator implements ConstraintValidator<Phone, String> {

    @Override
    public void initialize(Phone phone) {
       
    }


    @Override
    public boolean isValid(String phoneField, ConstraintValidatorContext cxt) {
        if (phoneField == null){
            return false;
        }

        return phoneField.matches("[0-9()-]*");
    }

}



5- Add the annotation to your bean.

Easy !!! Yeah :)