Java 正則表達式 之 注冊驗證


http://www.verejava.com/?id=16994944659329

package com.reg;

public class TestReg
{
	public static void main(String[] args)
	{
		System.out.println(testTel("+22861232233333"));
	}
	
	/**
	 * 5.	國際電話號碼驗證
			以數字或+開頭 
			后面的必須是數字長度在 12 到 13

	 */
	public static boolean testTel(String tel)
	{
		String regex="[+\\d]?\\d{12,13}";
		return tel.matches(regex);
	}
	
	/**
	 * 4.	注冊電子郵箱驗證
				郵箱地址必須包含@字符
				郵箱@的左邊必須以字母, 下划線, 數字開頭, 且必須有一個
				郵箱@的左邊除了開頭字母其他的可以是字母, 下划線, 數字, 點號 . 小杠 -
				郵箱@的右邊必須有 . 點號
				在 @ 和 . 之間必須以字母, 下划線, 數字開頭, 且除了開頭字母其他的可以是字母, 下划線, 數字, 點號 . 小杠 -
				在 . 點號后面至少有一個 字母, 下划線, 數字開頭

	 */
	public static boolean testEmail(String email)
	{
		String regex="(\\w+)([\\w+.-])*@(\\w+)([\\w+.-])*\\.\\w+";
		return email.matches(regex);
	}
	
	/**
	 * 身份證驗證
		身份證號碼必須為15位或18位數字
	 */
	public static boolean testIdentity(String identity)
	{
		String regex="\\d{15}|\\d{18}|\\d{17}X";
		return identity.matches(regex);
	}
	
	/**
	 * 2.	論壇注冊用戶名驗證
			必須以字母開頭
			只能包括 字母 , 下划線 , 數字
			長度必須在6 到 10 之間

	 */
	public static boolean checkUsername(String username)
	{
		//String regex="[a-zA-Z][0-9a-zA-Z_]{5,9}";
		//String regex="[a-zA-Z][\\da-zA-Z_]{5,9}";// \d  要轉成 \\d
		String regex="[a-zA-Z]\\w{5,9}";
		return username.matches(regex);
	}
	
	/**
	 * 1.	驗證碼必須是數字, 並且是4位數字
	 * @param telephone
	 */
	public static boolean testValidCode(String code)
	{
		//String regex="[0-9][0-9][0-9][0-9]";
		String regex="[0-9]{4}";
		return code.matches(regex);
	}
	
	public static void testTelephone2(String telephone)
	{
		String regex="1[0-9]{10}";
		boolean b=telephone.matches(regex);
		if(b)
		{
			System.out.println("有效電話號碼");
		}
		else
		{
			System.out.println("無效電話號碼");
		}
	}
	/**
	 * 題目: 注冊的時候, 驗證輸入手機號碼的有效性 
		要求: 
			必須是1開頭的
			長度為11位
			手機號碼必須是數字

	 * @param args
	 */
	public static void testTelephone(String telephone)
	{
		//是否是1開頭的
		if(!telephone.startsWith("1"))
		{
			System.out.println("電話號不是1開頭的");
		}else if(telephone.length()!=11)//判斷電話號碼是否 11 位
		{
			System.out.println("電話號碼不是11位的");
		}else
		{
			//手機號碼是否為數字
			String num="0123456789";
			char[] chars=telephone.toCharArray();
			boolean isValid=true;
			for(int i=0;i<chars.length;i++)
			{
				String s=String.valueOf(chars[i]);
				if(num.indexOf(s)<0)
				{
					isValid=false;
				}
			}
			if(isValid)
			{
				System.out.println("電話號碼輸入有效");
			}
			else
			{
				System.out.println("電話號碼輸入有無效數字");
			}
		}
	}
	
	
}

http://www.verejava.com/?id=16994944659329


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM