java正则表达式表单验证

来源:互联网 发布:java怎么创建多线程 编辑:程序博客网 时间:2024/06/05 11:02

java正则表达式表单验证类工具类(验证邮箱、手机号码、qq号码等)

这篇文章主要介绍了java使用正则表达式进行表单验证工具类,可以验证邮箱、手机号码、qq号码等方法,需要的朋友可以参考下

java使用正则表达式进行表单验证工具类,可以验证邮箱、手机号码、qq号码等。

[java] view plain copy
 print?
  1. package util;  
  2. import java.util.regex.Matcher;  
  3. import java.util.regex.Pattern;  
  4. /** 
  5.  * 使用正则表达式进行表单验证 
  6.  *  
  7.  */  
  8. public class RegexValidateUtil {  
  9.     static boolean flag = false;  
  10.     static String regex = "";  
  11.     public static boolean check(String str, String regex) {  
  12.  try {  
  13.      Pattern pattern = Pattern.compile(regex);  
  14.      Matcher matcher = pattern.matcher(str);  
  15.      flag = matcher.matches();  
  16.  } catch (Exception e) {  
  17.      flag = false;  
  18.  }  
  19.  return flag;  
  20.     }  
  21.     /** 
  22.      * 验证非空 
  23.      *  
  24.      * @param email 
  25.      * @return 
  26.      */  
  27.     public static boolean checkNotEmputy(String notEmputy) {  
  28.  regex = "^\\s*$";  
  29.  return check(notEmputy, regex) ? false : true;  
  30.     }  
  31.     /** 
  32.      * 验证邮箱 
  33.      *  
  34.      * @param email 
  35.      * @return 
  36.      */  
  37.     public static boolean checkEmail(String email) {  
  38.  String regex = "^\\w+[-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$ ";  
  39.  return check(email, regex);  
  40.     }  
  41.     /** 
  42.      * 验证手机号码 
  43.      *  
  44.      * 移动号码段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147 
  45.      * 联通号码段:130、131、132、136、185、186、145 
  46.      * 电信号码段:133、153、180、189 
  47.      *  
  48.      * @param cellphone 
  49.      * @return 
  50.      */  
  51.     public static boolean checkCellphone(String cellphone) {  
  52.  String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$";   
  53.  return check(cellphone, regex);  
  54.     }  
  55.     /** 
  56.      * 验证固话号码 
  57.      *  
  58.      * @param telephone 
  59.      * @return 
  60.      */  
  61.     public static boolean checkTelephone(String telephone) {  
  62.  String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";  
  63.  return  check(telephone, regex);  
  64.     }  
  65.     /** 
  66.      * 验证传真号码 
  67.      *  
  68.      * @param fax 
  69.      * @return 
  70.      */  
  71.     public static boolean checkFax(String fax) {  
  72.  String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";   
  73.  return check(fax, regex);  
  74.     }  
  75.    
  76.     /** 
  77.      * 验证QQ号码 
  78.      *  
  79.      * @param QQ 
  80.      * @return 
  81.      */  
  82.     public static boolean checkQQ(String QQ) {  
  83.  String regex = "^[1-9][0-9]{4,} $";  
  84.  return check(QQ, regex);  
  85.     }  
原创粉丝点击