Chandru
Chandru

Reputation: 5962

Restrict special characters in android password edittext

I am working on a project where the user is allowed to type only password with letters, alphabets and special characters like (@.#$%^&_-&*) alone in a edittext. I tried various methods like. **Note: space is strictly restricted

Method 1:

setting digits in layout as follows

android:digits="0,1,2,3,4,5,6,7,8,9,*@#$%_-\^.&<qwertzuiopasdfghjklyxcvbnmABCDEFGHIJKLMNOPQRSTUVWXYZ"

This method is working fine but i could able to type brackets'(', semicolon ';' and i could not type slash '\' (which i have added in the digits tag)

Method 2:

By trying regex with following method

public static boolean limitPasswordCharacters(String about){
        // UserName Validation Pattern String
        final Pattern USER_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9@.#$%^&*_&\\]+$");
        if(USER_NAME_PATTERN.matcher(about).matches()){
            return true;            
        }
        return false;
    }

But unfortunately gettting exception as

11-17 16:18:11.155: E/AndroidRuntime(15877): java.util.regex.PatternSyntaxException: Missing closing bracket in character class near index 22:
11-17 16:18:11.155: E/AndroidRuntime(15877): [a-zA-Z0-9@.#$%^&*_&\]

Upvotes: 2

Views: 5886

Answers (2)

Agil anbu
Agil anbu

Reputation: 81

Simply paste this line in your edittext

android:digits="0123456789qwertzuiopasdfghjklyxcvbnm " 

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174706

Change your pattern like below,

final Pattern USER_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9@.#$%^&*_&\\\\]+$");

In java regex, to mean a backslash, you need to escape it three times. Java consider this \\] as a lietral ] bracket.

Example:

String digits="0,1,2,3,4,5,6,7,8,9,*@#$%_-\\^.&<qwertzuiopasdfghjklyxcvbnmABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println(digits.matches("^[-a-zA-Z0-9@.#$%^&*_&,<\\\\]+$")); //true

Upvotes: 2

Related Questions