Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate Password Field in android?

Tags:

android

Hi I am very new for android and in my app I have Validations for Change password page.

That means the Password must contain minimum 8 characters at least 1 Alphabet, 1 Number and 1 Special Character, for this I tried the code below, but it's not working.

Please help me.

if(!isPasswordValidMethod(newPassword.getText().toString())){
           System.out.println("Not Valid");

                }else{

        System.out.println("Valid");
    }



     // Validate password
        private boolean isPasswordValidMethod(String password) {

            String yourString = newPassword.getText().toString();

            System.out.println("yourString is =" + yourString);

            boolean isValid = false;

            // ^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$
            // ^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z]{2,4}$

            String expression = "^(?=.*[A-Za-z])(?=.*\\\\d)(?=.*[$@$!%*#?&])[A-Za-z\\\\d$@$!%*#?&]{8,}$";
            CharSequence inputStr = password;

            Pattern pattern = Pattern.compile(expression, Pattern.CASE_INSENSITIVE);
            Matcher matcher = pattern.matcher(inputStr);
            if (matcher.matches()) {
                System.out.println("if");
                isValid = true;
            }else{
                System.out.println("else");
            }
            return isValid;
        }
like image 631
Krish Avatar asked Apr 12 '16 13:04

Krish


2 Answers

try following Code

 //*****************************************************************
public static boolean isValidPassword(final String password) {

    Pattern pattern;
    Matcher matcher;
    final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[A-Z])(?=.*[@#$%^&+=!])(?=\\S+$).{4,}$";
    pattern = Pattern.compile(PASSWORD_PATTERN);
    matcher = pattern.matcher(password);

    return matcher.matches();

}

And change your code to this

   if(newPassword.getText().toString().length()<8 &&!isValidPassword(newPassword.getText().toString())){
        System.out.println("Not Valid");
      }else{
       System.out.println("Valid");
    }
like image 168
mdDroid Avatar answered Sep 21 '22 13:09

mdDroid


public static boolean isValidPassword(String s) {
            Pattern PASSWORD_PATTERN
                    = Pattern.compile(
                    "[a-zA-Z0-9\\!\\@\\#\\$]{8,24}");

            return !TextUtils.isEmpty(s) && PASSWORD_PATTERN.matcher(s).matches();
        }

to use it,

if(isValidPassword(password)){ //password valid}

You can set whatever symbol that you allowed here

like image 43
yuzuriha Avatar answered Sep 19 '22 13:09

yuzuriha