Tuesday, June 2, 2015

JAVA Annotation for phone number validation of bean field

==== USE OF ANNOTATION ON BEAN FIELD ====
   @Phone
    public String getPhone() {
        return phone;
    }

==== PHONE NUMBER VALIDATION CLASS ===
import javax.validation.Constraint;
import javax.validation.Payload;
import javax.validation.ReportAsSingleViolation;
import javax.validation.constraints.Pattern;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * Created by baraole on 27/05/2015.
 */
@Documented
@Constraint(validatedBy = {})
@Pattern(regexp = "\\+?[0-9()]+")
@ReportAsSingleViolation
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
public @interface Phone {
    String message() default "not a well-formed phone number";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * Defines several {@code @Phone} annotations on the same element.
     */
    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
    @Retention(RUNTIME)
    @Documented
    public @interface List {
        Phone[] value();
    }
}

No comments: