Ank*_*ani 12 java phone-number hibernate-validator bean-validation
我有一个名为User的实体,我想验证手机号码字段
手机号码字段不是强制性的,可以留空,但应该是10位数字.
如果用户输入的长度小于10位,则应抛出错误.
以下是我的用户类.
public class User {
@Size(min=0,max=10)
private String mobileNo;
}
Run Code Online (Sandbox Code Playgroud)
当我如上所述使用@Sized注释时,我可以验证大于10的值,但如果用户输入的数字少于10位,则不会引发错误.
我的要求是,如果用户将mobileNo字段留空,该字段有效,但如果输入了值,则验证应确保输入的数字仅为10位数和10位数.
我应该使用哪个注释来满足此要求?
Pio*_*ski 27
@Size(min=10,max=10) 如果通过空白你的意思是null,我会做的.
如果您没有放置@NotNull注释,则null值将通过验证.
如果你的空白意味着空字符串,那么你需要使用@Pattern验证器:
@Pattern(regexp="(^$|[0-9]{10})")
Run Code Online (Sandbox Code Playgroud)
这匹配空字符串或10位数字.
小智 7
For those who are looking for a custom validator for phone numbers using libphonenumber
PhoneNumber.java libphonenumber requires locale for validation so we need to create a custom class for storing phone and regioncode
public class PhoneNumber {
@NotEmpty
private String value;
@NotEmpty
private String locale;
}
Run Code Online (Sandbox Code Playgroud)
@Phone Annotation Will be used to annotate fields for validation
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.*;
@Documented
@Constraint(validatedBy = PhoneNumberValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Phone {
String locale() default "";
String message() default "Invalid phone number";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
Run Code Online (Sandbox Code Playgroud)
PhoneNumberValidator.java It will check phone's validity for the provided region code
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
public class PhoneNumberValidator implements ConstraintValidator<Phone, PhoneNumber> {
@Override
public void initialize(Phone constraintAnnotation) {
}
@Override
public boolean isValid(PhoneNumber phoneNumber, ConstraintValidatorContext context) {
if(phoneNumber.getLocale()==null || phoneNumber.getValue()==null){
return false;
}
try{
PhoneNumberUtil phoneNumberUtil = PhoneNumberUtil.getInstance();
return phoneNumberUtil.isValidNumber(phoneNumberUtil.parse(phoneNumber.getValue(), phoneNumber.getLocale()));
}
catch (NumberParseException e){
return false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Usage
@Phone
private PhoneNumber phone;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25130 次 |
| 最近记录: |