Sunday 4 April 2021

Password Validation using regular expressions and matches() in Java

 Some websites impose certain rules for passwords. Suppose the password rules are as

follows: ¦ A password must have at least eight characters. ¦ A password consists of only letters and digits. Write main () method that prompts the user to enter a password and a static method isValidPassword() that expects a string argument and returns boolean type after validating the password.


Solution:

package p1;


import java.util.Scanner;

class Password

{

String pass;


static boolean isValidPassword(String p)

{

if((p.length()>=8) &&p.matches("[a-zA-Z0-9]*"))

{

return true;

}   

else

{ return false; }

}

}

public class Passwordrule

{

public static void main(String[] args) 

{

String pas;

      Scanner s=new Scanner(System.in);

System.out.println("Enter the password");

pas=s.nextLine();

System.out.println("value in pas is"+pas);

boolean res=Password.isValidPassword(pas);

if(res==true)  

{

System.out.println("password is valid");

}

else

{

System.out.println("password is invalid");

}    

}

}

For >=8 charcters length password to have atleast one digit, atleast one alphabet and no spaces, the regular expression inside matches would be
if((p.length()>=8) &&p.matches(".*[a-zA-Z].*") &&p.matches(".*[0-9].*")&&(!(p.matches(".*\\s.*"))))

No comments:

Post a Comment