Android 密碼校驗,字串中必須包含字母或者數字
阿新 • • 發佈:2019-01-03
下面是Util類的內容提供了三種密碼規則的校驗和一個判斷輸入型別的方法
/** * Created by zhangshun on 2016/8/18. */ public class PwdCheckUtil { /** * 規則1:至少包含大小寫字母及數字中的一種 * 是否包含 * * @param str * @return */ public static boolean isLetterOrDigit(String str) { boolean isLetterOrDigit = false;//定義一個boolean值,用來表示是否包含字母或數字 for (int i = 0; i < str.length(); i++) { if (Character.isLetterOrDigit(str.charAt(i))) { //用char包裝類中的判斷數字的方法判斷每一個字元 isLetterOrDigit = true; } } String regex = "^[a-zA-Z0-9]+$"; boolean isRight = isLetterOrDigit && str.matches(regex); return isRight; } /** * 規則2:至少包含大小寫字母及數字中的兩種 * 是否包含 * * @param str * @return */ public static boolean isLetterDigit(String str) { boolean isDigit = false;//定義一個boolean值,用來表示是否包含數字 boolean isLetter = false;//定義一個boolean值,用來表示是否包含字母 for (int i = 0; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) { //用char包裝類中的判斷數字的方法判斷每一個字元 isDigit = true; } else if (Character.isLetter(str.charAt(i))) { //用char包裝類中的判斷字母的方法判斷每一個字元 isLetter = true; } } String regex = "^[a-zA-Z0-9]+$"; boolean isRight = isDigit && isLetter && str.matches(regex); return isRight; } /** * 規則3:必須同時包含大小寫字母及數字 * 是否包含 * * @param str * @return */ public static boolean isContainAll(String str) { boolean isDigit = false;//定義一個boolean值,用來表示是否包含數字 boolean isLowerCase = false;//定義一個boolean值,用來表示是否包含字母 boolean isUpperCase = false; for (int i = 0; i < str.length(); i++) { if (Character.isDigit(str.charAt(i))) { //用char包裝類中的判斷數字的方法判斷每一個字元 isDigit = true; } else if (Character.isLowerCase(str.charAt(i))) { //用char包裝類中的判斷字母的方法判斷每一個字元 isLowerCase = true; } else if (Character.isUpperCase(str.charAt(i))) { isUpperCase = true; } } String regex = "^[a-zA-Z0-9]+$"; boolean isRight = isDigit && isLowerCase && isUpperCase && str.matches(regex); return isRight; } /** * 判斷EditText輸入的數字、中文還是字母方法 */ public static void whatIsInput(Context context, EditText edInput) { String txt = edInput.getText().toString(); Pattern p = Pattern.compile("[0-9]*"); Matcher m = p.matcher(txt); if (m.matches()) { Toast.makeText(context, "輸入的是數字", Toast.LENGTH_SHORT).show(); } p = Pattern.compile("[a-zA-Z]"); m = p.matcher(txt); if (m.matches()) { Toast.makeText(context, "輸入的是字母", Toast.LENGTH_SHORT).show(); } p = Pattern.compile("[\u4e00-\u9fa5]"); m = p.matcher(txt); if (m.matches()) { Toast.makeText(context, "輸入的是漢字", Toast.LENGTH_SHORT).show(); } } }