package com.pt.modules.contract.utils.Customannotations; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import javax.validation.Constraint; import javax.validation.Payload; /** * * @description 功能描述: 自定义注解身份证号格式校验 * @author 作 者: * @param 参 数: * @Createdate 建立日期: 2016年12月28日下午2:34:44 */ @Constraint(validatedBy = IsNumberFormatValidator.class) //具体的实现 @Target( { java.lang.annotation.ElementType.METHOD, java.lang.annotation.ElementType.FIELD }) @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Documented public @interface IsNumberFormat { String message() default "{org.hibernate.validator.constraints.NotEmpty.message}"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
package com.pt.modules.contract.utils.Customannotations; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import com.pt.modules.contract.utils.IdcardValidator; /** * * @description 功能描述: 自定义注解身份证号格式校验 * @param 参 数: * @Createdate 建立日期: 2016年12月28日下午2:33:38 */ public class IsNumberFormatValidator implements ConstraintValidator<IsNumberFormat, String>{ @Override public boolean isValid(String IdNumber, ConstraintValidatorContext constraintValidatorContext) { String message=constraintValidatorContext.getDefaultConstraintMessageTemplate(); if(IdNumber != null){ IdcardValidator p = new IdcardValidator(); boolean fglg = p.isValidatedAllIdcard(IdNumber); if(fglg==true){ return true; } } constraintValidatorContext.disableDefaultConstraintViolation();//禁用默认的message的值 constraintValidatorContext .buildConstraintViolationWithTemplate(message+IdNumber).addConstraintViolation(); return false; } @Override public void initialize(IsNumberFormat constraintAnnotation) { } }
@IsNumberFormat(message="属性名--lenNumber,出借人身份证号格式不正确--") private String lenNumber;
try { BeanValidators.validateWithException(validator, lendInfo);// 报文校验 }catch (ConstraintViolationException e) { BeanValidators.extractMessage(e).toString(); }