Regular Expression In Android for Password Field

前端 未结 10 1141
执念已碎
执念已碎 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:12

    As an addition to the answers already given, I would suggest a different route for identifying special characters and also would split up the check for the different rules.

    First splitting it up: Instead of making one big rule, split it and check every rule separately, so that you are able to provide feedback to the user as to what exactly is wrong with his password. This might take a bit longer but in something like a password checkup this will not be noticable. Also, this way the conditions are more readable.

    Secondly, instead of checking for a list of special characters, you could flip it and check if the password contains any characters that are neither letters of the latin alphabet (a-zA-Z) nor digits (0-9). That way you don't "forget" special characters. For example, lets say you check specifically but in your check you forget a character like "{”. With this approach, this can't happen. You can extend that list by things you don't consider to be special characters explicitly, for example a space. In kotlin, it would look like this:

    val errorText = when {
        /* Rule 1 */
        !password.contains(Regex("[A-Z]")) -> "Password must contain one capital letter"
        /* Rule 2 */
        !password.contains(Regex("[0-9]")) -> "Password must contain one digit"
        /* Rule 3, not counting space as special character */
        !password.contains(Regex("[^a-zA-Z0-9 ]")) -> "Password must contain one special character"
        else -> null
    }
    

    Depending on your encoding, you can also use regex and define your special characters using ranges of hex codes like

    Reges("[\x00-\x7F]")
    

提交回复
热议问题