Regular Expression In Android for Password Field

前端 未结 10 1105
执念已碎
执念已碎 2020-12-13 09:56

How can i validating the EditText with Regex by allowing particular characters . My condition is :

Password Rule:

  1. On

相关标签:
10条回答
  • 2020-12-13 10:13

    None of the above worked for me.

    What worked for me:

    fun isValidPasswordFormat(password: String): Boolean {
        val passwordREGEX = Pattern.compile("^" +
            "(?=.*[0-9])" +         //at least 1 digit
            "(?=.*[a-z])" +         //at least 1 lower case letter
            "(?=.*[A-Z])" +         //at least 1 upper case letter
            "(?=.*[a-zA-Z])" +      //any letter
            "(?=.*[@#$%^&+=])" +    //at least 1 special character
            "(?=\\S+$)" +           //no white spaces
            ".{8,}" +               //at least 8 characters
            "$");
        return passwordREGEX.matcher(password).matches()
    }
    

    Source: Coding in Flow

    Hope it helps someone.

    0 讨论(0)
  • 2020-12-13 10:17

    And for the Kotlin lovers :

    fun isValidPassword(password: String?) : Boolean {
       password?.let {
           val passwordPattern = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{4,}$"
           val passwordMatcher = Regex(passwordPattern)
    
           return passwordMatcher.find(password) != null
       } ?: return false
    }
    
    0 讨论(0)
  • 2020-12-13 10:24

    Most common password validation is

    1. At least 8 character
    2. Require numbers
    3. Require special character
    4. Require uppercase letters
    5. Require lowercase letters

    Regex:

    ^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\/%§"&“|`´}{°><:.;#')(@_$"!?*=^-]).{8,}$
    

    Kotlin code:

        val PASSWORD_REGEX_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[\\\/%§"&“|`´}{°><:.;#')(@_$"!?*=^-]).{8,}$"
    
        fun isValidPassword(password: String?): Boolean {
            val pattern: Pattern =
                Pattern.compile(PASSWORD_REGEX_PATTERN)
            val matcher: Matcher = pattern.matcher(password)
            return matcher.matches()
        }
    

    online regex validator to check it:

    • https://regex101.com/
    • https://www.freeformatter.com/java-regex-tester.html#ad-output
    0 讨论(0)
  • 2020-12-13 10:26
    try {
        if (subjectString.matches("^(?=.*[@$%&#_()=+?»«<>£§€{}\\[\\]-])(?=.*[A-Z])(?=.*[a-z])(?=.*\\d).*(?<=.{4,})$")) {
            // String matched entirely
        } else {
            // Match attempt failed
        } 
    } catch (PatternSyntaxException ex) {
        // Syntax error in the regular expression
    }
    
    
    (?=.*[@\$%&#_()=+?»«<>£§€{}.[\]-]) -> must have at least 1 special character
    (?=.*[A-Z])   -> Must have at least 1 upper case letter
    (?=.*[a-z])   -> Must have at least 1 lower case letter
    (?=.*\\d)     -> Must have at least 1 digit
    (?<=.{4,})$") -> Must be equal or superior to 4 chars.
    
    0 讨论(0)
提交回复
热议问题