@Valid注解

@Valid注解_第1张图片
除此之外还可以自定义验证信息的要求

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

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

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

    @Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER, ElementType.TYPE_USE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    public @interface List {
		Phone[] value();
    }
}

public class PhoneValidator implements ConstraintValidator<Phone,Object> {
	@Override
	public boolean isValid(Object phone, ConstraintValidatorContext constraintValidatorContext) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		String s1 = (String) phone;
		String s2="^[1](([3|5|8][\\d])|([4][4,5,6,7,8,9])|([6][2,5,6,7])|([7][^9])|([9][1,8,9]))[\\d]{8}$";// 验证手机号
		if(StringUtils.isNotBlank(s1)){
			p = Pattern.compile(s2);
			m = p.matcher(s1);
			b = m.matches();
		}
		return b;
	}
}

	/**
	 * 联系方式
	 */
	@Phone
	@ApiModelProperty(value = "联系方式")
	private String frLxdh;

手机号正则表达式: ^(?:0|86|\\+86)?1[3-9]\\d{9}$
座机号正则表达式:^(0\\d{2,3}-[1-9]\\d{6,7})$
身份证正则表达式(15/18位通用):(^[1-9]\\d{5}(18|19|20)\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}[0-9Xx]$)|(^[1-9]\\d{5}\\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\\d{3}$)
统一信用代码正则表达式(15/18位通用):^([0-9A-HJ-NPQRTUWXY]{2}\d{6}[0-9A-HJ-NPQRTUWXY]{10}|[1-9]\d{14})$
车牌号正则表达式:^([京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[a-zA-Z](([DF]((?![IO])[a-zA-Z0-9](?![IO]))[0-9]{4})|([0-9]{5}[DF]))|[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1})$

你可能感兴趣的:(代码,java)