基于注解编程1-手机号格式验证

2020-12-03  本文已影响0人  指尖de旋律

if else虽然永不过时,但是工作讲究能偷懒必须偷懒,所以当遇上要求进行手机号验证时,建议直接使用注解的方式进行数据格式验证,简单,易维护,下面上干货

手机格式验证注解类 phone.java

import static java.lang.annotation.ElementType.ANNOTATION_TYPE;
import static java.lang.annotation.ElementType.CONSTRUCTOR;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.ElementType.METHOD;
import static java.lang.annotation.ElementType.PARAMETER;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.constraints.Pattern;

import org.springframework.messaging.handler.annotation.Payload;
import ....valid.Phone.List;
import ....validation.PhoneValidator;

@Documented
@Constraint(validatedBy = { PhoneValidator.class })
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE })
@Retention(RUNTIME)
@Repeatable(List.class)
public @interface Phone {
    
    String message() default "手机号格式不正确";

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

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

    /**
     * @return an additional regular expression the annotated element must match. The default
     * is any string ('.*')
     */
    String regexp() default ".*";

    /**
     * @return used in combination with {@link #regexp()} in order to specify a regular
     * expression option
     */
    Pattern.Flag[] flags() default { };

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

手机格式验证方法 PhoneValidator.java

import static java.util.regex.Pattern.CASE_INSENSITIVE;

import java.util.regex.Pattern;

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

import ....valid.Phone;

public class PhoneValidator implements ConstraintValidator<Phone, CharSequence> {

    private final Pattern mobilePattern = Pattern.compile("(\\+\\d+)?1[3456789]\\d{9}$", CASE_INSENSITIVE);
    
    @Override
    public void initialize(Phone constraintAnnotation) {
        
    }
    
    @Override
    public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
        if ( value == null || value.length() == 0 ) {
            return false;
        }
        return mobilePattern.matcher(value).matches();
    }

}
上一篇 下一篇

猜你喜欢

热点阅读