1.通常我们的web程序里面,必不可少的就是数据验证了。在此,整理了一个小工具类,可直接使用。
2.在数据验证,必不可少的就是正则表达式了,相关操作参考一下
https://www.cnblogs.com/gdwkong/articles/7782331.html
3.一般我们的正则匹配是不用改变的,所以我们要在类中将正则匹配固定死,即使用 private final static 。且我们的类方法是面向外部调用,此时,为了减少资源的使用,可将方法也写成静态方法。到时候直接类.方法名 即可,方便又省事。
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Ereg {
private final static String CheckDigitRex = "^[0-9]*$";//验证纯数字 "[0-9]+";
private final static String MailboxVerificationRex = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";//邮箱验证
private final static String PhoneNumberVerificationRex1 = "^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\\d{8}$";//手机号码
private final static String PhoneNumberVerificationRex2 = "\\d{3}-\\d{8}|\\d{4}-\\d{7}";//固定号码
private final static String PasswordAuthentificationRex = "^[a-zA-Z]\\w{5,17}$";//密码验证 密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线)
private final static String PasswordAuthentificationRex2 = "^\\d{6,12}$";//为了项目方便,这里使用简单的密码验证即可。
public static boolean CheckDigit(String str){//数值验证
Pattern pattern = Pattern.compile(Ereg.CheckDigitRex);
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
public static boolean MailboxVerification(String str){//邮箱验证
Pattern pattern = Pattern.compile(Ereg.MailboxVerificationRex);
Matcher matcher = pattern.matcher(str);
return matcher.matches();
}
public static boolean PhoneNumberVerification(String str){//电话号码验证
boolean flage = false;
Pattern pattern1 = Pattern.compile(Ereg.PhoneNumberVerificationRex1);
Pattern pattern2 = Pattern.compile(Ereg.PhoneNumberVerificationRex2);
Matcher matcher1 = pattern1.matcher(str);
Matcher matcher2 = pattern1.matcher(str);
if (matcher1.matches() || matcher2.matches()){
flage = true;
}
return flage;
}
//密码规则验证
public static boolean PasswordAuthentification(String str){//电话号码验证
boolean flage = false;
//这里密码验证只是写了认证密码多少位数而已
Pattern pattern1 = Pattern.compile(Ereg.PasswordAuthentificationRex);//
Matcher matcher1 = pattern1.matcher(str);
Pattern pattern2 = Pattern.compile(Ereg.PasswordAuthentificationRex2);//使用简单化密码
Matcher matcher2 = pattern2.matcher(str);
if (matcher1.matches() || matcher2.matches()){
flage = true;
}
return flage;
}
public static void main(String[] args) {
String phone = "15667533671";
String num = "50";
String email = "java_py_meimei@qq.com";
String password = "abc1234565";
String password2 = "123456";
if (PasswordAuthentification(password)){
System.out.println("正常密码合格");
}else {
System.out.println("no");
}
if (PasswordAuthentification(password2)){
System.out.println("普通数字密码合格");
}else {
System.out.println("no");
}
if (CheckDigit(num)){
System.out.println("yes");
}else {
System.out.println("no");
}
if (MailboxVerification(email)){
System.out.println("邮箱正确");
}else {
System.out.println("no");
}
if (PhoneNumberVerification(phone)){
System.out.println("电话号码正确");
}else {
System.out.println("no");
}
}
}