1. 获取随机验证码
public class ValidateCodeUtils {
public static Integer generateValidateCode(int length){
Integer code =null;
if(length == 4){
code = new Random().nextInt(9999);
if(code < 1000){
code = code + 1000;
}
}else if(length == 6){
code = new Random().nextInt(999999);
if(code < 100000){
code = code + 100000;
}
}else{
throw new RuntimeException("只能生成4位或6位数字验证码");
}
return code;
}
public static String generateValidateCode4String(int length){
Random rdm = new Random();
String hash1 = Integer.toHexString(rdm.nextInt());
String capstr = hash1.substring(0, length);
return capstr;
}
}
2.格式验证工具类
public class RegexUtils {
public static boolean isPhoneInvalid(String phone){
return mismatch(phone, RegexPatterns.PHONE_REGEX);
}
public static boolean isEmailInvalid(String email){
return mismatch(email, RegexPatterns.EMAIL_REGEX);
}
public static boolean isCodeInvalid(String code){
return mismatch(code, RegexPatterns.VERIFY_CODE_REGEX);
}
private static boolean mismatch(String str, String regex){
if (StrUtil.isBlank(str)) {
return true;
}
return !str.matches(regex);
}
}
public abstract class RegexPatterns {
public static final String PHONE_REGEX = "^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$";
public static final String EMAIL_REGEX = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
public static final String PASSWORD_REGEX = "^\\w{4,32}$";
public static final String VERIFY_CODE_REGEX = "^[a-zA-Z\\d]{6}$";
}