Regular Expression In Android for Password Field

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

    Try this.

    (/^(?=.*\d)(?=.*[A-Z])([@$%&#])[0-9a-zA-Z]{4,}$/)
    
    
    (/^
    (?=.*\d)                //should contain at least one digit
    (?=.*[@$%&#])           //should contain at least one special char
    (?=.*[A-Z])             //should contain at least one upper case
    [a-zA-Z0-9]{4,}         //should contain at least 8 from the mentioned characters
    $/)
    
    0 讨论(0)
  • 2020-12-13 10:01

    you can use the class Patern than Matcher for every checking format.

    I give you an exemple of use :

            Pattern pattern = Pattern.compile(".+@.+\\.[a-z]+");
            Matcher matcher = pattern.matcher(myEmailString);
            if (!myEmailString.contains("@") || !matcher.matches()) {
                // error in the email : do staff 
                myEmailView.setError("invalid email !");
    
            }
    
    0 讨论(0)
  • 2020-12-13 10:04

    I'm too late to answer but still it may help you.

    I've worked with Kotlin.

    Add following function.

    private fun isValidPassword(password: String): Boolean {
        val pattern: Pattern
        val matcher: Matcher
        val specialCharacters = "-@%\\[\\}+'!/#$^?:;,\\(\"\\)~`.*=&\\{>\\]<_"
        val PASSWORD_REGEX = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[$specialCharacters])(?=\\S+$).{8,20}$"
        pattern = Pattern.compile(PASSWORD_REGEX)
        matcher = pattern.matcher(password)
        return matcher.matches()
    }
    

    Function description:

    • (?=.*[0-9]) # a digit must occur at least once
    • (?=.*[a-z]) # a lower case letter must occur at least once
    • (?=.*[A-Z]) # an upper case letter must occur at least once
    • (?=.[-@%[}+'!/#$^?:;,(")~`.=&{>]<_]) # a special character must occur at least once replace with your special characters
    • (?=\S+$) # no whitespace allowed in the entire string .{8,} # anything, at least six places though

    You can modify it as needed.

    Hope it helps.

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

    All of the other answers are good, but the implementation of special characters were a bit too messy for my taste. I used Unicode for special characters instead.

    I used special characters specified in the OWASP website.

    Kotlin:

    val SPECIAL_CHARACTERS_REGEX =
        "?=.*[\\u0020-\\u002F\\u003A-\\u0040\\u005B-\\u0060\\u007B-\\u007E]"
    val PASSWORD_REGEX =
        "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])($SPECIAL_CHARACTERS_REGEX).{8,}\$"
    
    fun isValidPassword(password: String) = Pattern.matches(PASSWORD_REGEX, password)
    
    0 讨论(0)
  • 2020-12-13 10:08

    Try this may helps

    ^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{4,}$
    

    How it works?

    ^                 # start-of-string
    (?=.*[0-9])       # a digit must occur at least once
    (?=.*[a-z])       # a lower case letter must occur at least once
    (?=.*[A-Z])       # an upper case letter must occur at least once
    (?=.*[@#$%^&+=])  # a special character must occur at least once you can replace with your special characters
    (?=\\S+$)          # no whitespace allowed in the entire string
    .{4,}             # anything, at least six places though
    $                 # end-of-string
    

    How to Implement?

    public class MainActivity extends Activity {
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            final EditText editText = (EditText) findViewById(R.id.edtText);
            Button btnCheck = (Button) findViewById(R.id.btnCheck);
    
            btnCheck.setOnClickListener(new OnClickListener() {
    
                @Override
                public void onClick(View arg0) {
                    if (isValidPassword(editText.getText().toString().trim())) {
                        Toast.makeText(MainActivity.this, "Valid", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(MainActivity.this, "InValid", Toast.LENGTH_SHORT).show();
                    }
                }
            });
    
        }
    
        public boolean isValidPassword(final String password) {
    
            Pattern pattern;
            Matcher matcher;
    
            final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{4,}$";
    
            pattern = Pattern.compile(PASSWORD_PATTERN);
            matcher = pattern.matcher(password);
    
            return matcher.matches();
    
        }
    
    }
    
    0 讨论(0)
  • 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]")
    
    0 讨论(0)
提交回复
热议问题