javaRegex表單驗證類工具類(驗證郵箱、手機號碼、qq號碼等)_java

來源:互聯網
上載者:User

java使用Regex進行表單驗證工具類,可以驗證郵箱、手機號碼、qq號碼等

複製代碼 代碼如下:

package util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 使用Regex進行表單驗證
 *
 */

public class RegexValidateUtil {
    static boolean flag = false;
    static String regex = "";

    public static boolean check(String str, String regex) {
 try {
     Pattern pattern = Pattern.compile(regex);
     Matcher matcher = pattern.matcher(str);
     flag = matcher.matches();
 } catch (Exception e) {
     flag = false;
 }
 return flag;
    }

    /**
     * 驗證非空
     *
     * @param email
     * @return
     */
    public static boolean checkNotEmputy(String notEmputy) {
 regex = "^\\s*$";
 return check(notEmputy, regex) ? false : true;
    }

    /**
     * 驗證郵箱
     *
     * @param email
     * @return
     */
    public static boolean checkEmail(String email) {
 String regex = "^\\w+[-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$ ";
 return check(email, regex);
    }

    /**
     * 驗證手機號碼
     *
     * 移動號碼段:139、138、137、136、135、134、150、151、152、157、158、159、182、183、187、188、147
     * 聯通號碼段:130、131、132、136、185、186、145
     * 電訊號碼段:133、153、180、189
     *
     * @param cellphone
     * @return
     */
    public static boolean checkCellphone(String cellphone) {
 String regex = "^((13[0-9])|(14[5|7])|(15([0-3]|[5-9]))|(18[0,5-9]))\\d{8}$"; 
 return check(cellphone, regex);
    }

    /**
     * 驗證固話號碼
     *
     * @param telephone
     * @return
     */
    public static boolean checkTelephone(String telephone) {
 String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$";
 return  check(telephone, regex);
    }

    /**
     * 驗證傳真號碼
     *
     * @param fax
     * @return
     */
    public static boolean checkFax(String fax) {
 String regex = "^(0\\d{2}-\\d{8}(-\\d{1,4})?)|(0\\d{3}-\\d{7,8}(-\\d{1,4})?)$"; 
 return check(fax, regex);
    }

    /**
     * 驗證QQ號碼
     *
     * @param QQ
     * @return
     */
    public static boolean checkQQ(String QQ) {
 String regex = "^[1-9][0-9]{4,} $";
 return check(QQ, regex);
    }
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.