- java regex pattern validate password
- Example
- Output
- Валидация пароля с помощью регулярного выражения
- Пример использования регулярного выражения
- Тест регулярного выражения
- Java Regex Password Validation Example
- Password Validation Program in Java
- The entire code snippet is :
- Validate password in java
- Using regex
java regex pattern validate password
This regular expression refers to a pattern with at least one digit, one upper case letter, one lower case letter and one special symbol (“@#$%”).
Example
package com.w3spoint; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexTest { private static final String PATTERN = "((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).)"; public static void main(String args[]){ ListString> values = new ArrayListString>(); values.add("jaisingh1A@"); values.add("Sjai12$"); values.add("jaiA@"); values.add("jai*"); Pattern pattern = Pattern.compile(PATTERN); for (String value : values){ Matcher matcher = pattern.matcher(value); if(matcher.matches()){ System.out.println("Password "+ value +" is valid"); }else{ System.out.println("Password "+ value +" is invalid"); } } } }
package com.w3spoint; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexTest < private static final String PATTERN = "((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).)"; public static void main(String args[]) < Listvalues = new ArrayList(); values.add("jaisingh1A@"); values.add("Sjai12$"); values.add("jaiA@"); values.add("jai*"); Pattern pattern = Pattern.compile(PATTERN); for (String value : values)< Matcher matcher = pattern.matcher(value); if(matcher.matches())< System.out.println("Password "+ value +" is valid"); >else < System.out.println("Password "+ value +" is invalid"); >> > >
Output
Password jaisingh1A@ is valid Password Sjai12$ is valid Password jaiA@ is invalid Password jai* is invalid
Password jaisingh1A@ is valid Password Sjai12$ is valid Password jaiA@ is invalid Password jai* is invalid
Валидация пароля с помощью регулярного выражения
С татья содержит пример валидации пароля с помощью регулярного выражения. Тестирование регулярного выражения проводится с использованием библиотеки TextNG.
Регулярное выражение для тестирования пароля:
Объяснение регулярного выражения:
( # Начало группы (?=.*d) # Должен содержать цифру от 0 до 9 (?=.*[a-z]) # Должен содержать символ латинницы в нижем регистре (?=.*[A-Z]) # Должен содержать символ латинницы в верхнем регистре (?=.*[@#$%]) # Должен содержать специальный символ из списка "@#$%" . # Совпадает с предыдущими условиями # Длина - от 6 до 20 символов ) # Конец группы
Описанный шаблон определяет следующие требования к паролю: он должен содержать от 6 до 20 символов, в качестве символов могут использоваться: цифры, латинница в нижем и верхнем регистрах и специальные символы из списка «»№;%». При этом в пароле должен присутствовать хотя бы один символ из каждой из обозначенных групп.
Таким образом, данному шаблону удовлетворяют следующие пароли:
Пароли, которые не удовлетворяют нашим требованиям:
- mY1A@ — слишком короткий, пароль должен состоять минимум из 6-ти символов
- j4web12@ — должен быть хотя бы один символ латинницы в верхнем регистре
- J4WebRu12* — символ «*» не разрешается
- JForWeb$$ — должна быть хотя бы одна цифра
- J4WEB12$ — должен быть хотя бы один символ латинницы в нижнем регистре
Пример использования регулярного выражения
package ru.j4web.examples.java.regex.regexpasswordexample; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PasswordValidator < private static final String PASSWORD_PATTERN = "((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).)"; private final Pattern pattern; private Matcher matcher; public PasswordValidator() < pattern = Pattern.compile(PASSWORD_PATTERN); >public boolean validate(String password) < matcher = pattern.matcher(password); return matcher.matches(); >>
Тест регулярного выражения
package ru.j4web.examples.java.regex.regexpasswordexample; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; public class PasswordValidatorTest < private PasswordValidator passwordValidator; public PasswordValidatorTest() < >@BeforeClass public void setUpClass() throws Exception < passwordValidator = new PasswordValidator(); >@DataProvider public Object[][] validPasswordProvider() < return new Object[][]< < new String[]< "J4We#b", "12j4Web#$", "$http###J4Web%Ru", "%ThisIs$tr0ngPass%" >> >; > @DataProvider public Object[][] invalidPasswordProvider() < return new Object[][]< < new String[]< "mY1A@", "j4web12@", "J4WebRu12*", "JForWeb$$", "J4WEB12$" >> >; > @Test(dataProvider = "validPasswordProvider") public void validPasswordTest(String[] passwords) < for (String password : passwords) < boolean valid = passwordValidator.validate(password); System.out.println("Password "" + password + "" is valid: " + valid); Assert.assertEquals(true, valid); >> @Test(dataProvider = "invalidPasswordProvider") public void invalidPasswordTest(String[] passwords) < for (String password : passwords) < boolean valid = passwordValidator.validate(password); System.out.println("Password "" + password + "" is valid: " + valid); Assert.assertEquals(false, valid); >> >
------------------------------------------------------- T E S T S ------------------------------------------------------- Running ru.j4web.examples.java.regex.regexpasswordexample.PasswordValidatorTest Password "mY1A@" is valid: false Password "j4web12@" is valid: false Password "J4WebRu12*" is valid: false Password "JForWeb$$" is valid: false Password "J4WEB12$" is valid: false Password "J4We#b" is valid: true Password "12j4Web#$" is valid: true Password "$http###J4Web%Ru" is valid: true Password "%ThisIs$tr0ngPass%" is valid: true Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.745 sec Results : Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
Java Regex Password Validation Example
Password validation is the need of almost all the applications today. There are various ways to do validate passwords from writing everything manually to use third party available APIs. In this Java regex password validation tutorial, We are building password validator using regular expressions.
1. Regex for password validation
Above regular expression has following sections:
(?=.*[a-z]) : This matches the presence of at least one lowercase letter. (?=.*d) : This matches the presence of at least one digit i.e. 0-9. (?=.*[@#$%]) : This matches the presence of at least one special character. ((?=.*[A-Z]) : This matches the presence of at least one capital letter. : This limits the length of password from minimum 6 letters to maximum 16 letters.
Ordering of top 4 sections can be changed or they can even dropped out from final regular expression. This fact can be used to build our password validator programmatically.
2. Java program to validate password using regex
We are making the our validator configurable so that one can put the limits based on needs. Like if we want to force at least one special character, but not any capital letter, we can pass the required arguments accordingly.
package com.howtodoinjava.regex; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PasswordValidator < private static PasswordValidator INSTANCE = new PasswordValidator(); private static String pattern = null; /** * No one can make a direct instance * */ private PasswordValidator() < //do nothing >/** * Force the user to build a validator using this way only * */ public static PasswordValidator buildValidator( boolean forceSpecialChar, boolean forceCapitalLetter, boolean forceNumber, int minLength, int maxLength) < StringBuilder patternBuilder = new StringBuilder("((?=.*[a-z])"); if (forceSpecialChar) < patternBuilder.append("(?=.*[@#$%])"); >if (forceCapitalLetter) < patternBuilder.append("(?=.*[A-Z])"); >if (forceNumber) < patternBuilder.append("(?=.*d)"); >patternBuilder.append(".)"); pattern = patternBuilder.toString(); return INSTANCE; > /** * Here we will validate the password * */ public static boolean validatePassword(final String password) < Pattern p = Pattern.compile(pattern); Matcher m = p.matcher(password); return m.matches(); >>
3. Unit test password validation
So our password validator is ready. Lets test it with some JUnit test cases.
package com.howtodoinjava.regex; import junit.framework.Assert; import org.junit.Test; @SuppressWarnings("static-access") public class TestPasswordValidator < @Test public void testNormalPassword() < PasswordValidator validator = PasswordValidator.buildValidator(false, false, false, 6, 14); Assert.assertTrue(validator.validatePassword("howtodoinjava")); Assert.assertTrue(validator.validatePassword("howtodoin")); //Sort on length Assert.assertFalse(validator.validatePassword("howto")); >@Test public void testForceNumeric() < PasswordValidator validator = PasswordValidator.buildValidator(false,false, true, 6, 16); //Contains numeric Assert.assertTrue(validator.validatePassword("howtodoinjava12")); Assert.assertTrue(validator.validatePassword("34howtodoinjava")); Assert.assertTrue(validator.validatePassword("howtodo56injava")); //No numeric Assert.assertFalse(validator.validatePassword("howtodoinjava")); >@Test public void testForceCapitalLetter() < PasswordValidator validator = PasswordValidator.buildValidator(false,true, false, 6, 16); //Contains capitals Assert.assertTrue(validator.validatePassword("howtodoinjavA")); Assert.assertTrue(validator.validatePassword("Howtodoinjava")); Assert.assertTrue(validator.validatePassword("howtodOInjava")); //No capital letter Assert.assertFalse(validator.validatePassword("howtodoinjava")); >@Test public void testForceSpecialCharacter() < PasswordValidator validator = PasswordValidator.buildValidator(true,false, false, 6, 16); //Contains special char Assert.assertTrue(validator.validatePassword("howtod@injava")); Assert.assertTrue(validator.validatePassword("@Howtodoinjava")); Assert.assertTrue(validator.validatePassword("howtodOInjava@")); //No special char Assert.assertFalse(validator.validatePassword("howtodoinjava")); >>
In this post we learned about password validation using Java regular expression, which is capable of validating alphanumeric and special characters, including maximun and minimum password length.
Password Validation Program in Java
Hello everyone, in today’s tutorial I will be telling about how to do password validation in Java with simple code snippets using regular expression.
Below is the Java snippet for validation:
static final String REG = "^(?=.*\\d)(?=\\S+$)(?=.*[@#$%^&+=])(?=.*[a-z])(?=.*[A-Z]).$";
This all that is needed for mentioning our condition for the password.
- (?=.*\\d) – at least 1 digit.
- (?=\\S+$) – no white-space
- (?=.*[@#$%^&+=]) – at least one special symbol (only the ones given within the [ ]).
- (?=.*[a-z]) -at least one lower case letter.
- (?=.*[A-Z]) – at least one upper case letter.
- . – minimum 8 and, maximum of 10 letters (can change to any convenient length).
- $ – end of the string.
- ^ – beginning of the string.
So REG should match all of the above criteria.
Static is used for the constant variable. Final variable’s value can’t be modified
static final Pattern PATTERN = Pattern.compile(REG);
PATTERN.compile is a method of Pattern class in Java to match text against the regular expression more than once.
Below is code for the main section where we give a password and check if its matching our criteria of validation or not.
PATTERN.matcher is used to search operation on text for regular expression.
public static void main(String[] args) < String pass /cdn-cgi/l/email-protection" data-cfemail="4b78050b391e">[email protected] 0218"; if (PATTERN.matcher(pass).matches()) < System.out.print("The Password " + pass + " is valid"); >else < System.out.print("The Password " + pass + " is invalid"); >>
The entire code snippet is :
import java.util.regex.Pattern; class Main < static final String REG = "^(?=.*\\d)(?=\\S+$)(?=.*[@#$%^&+=])(?=.*[a-z])(?=.*[A-Z]).$"; private static final Pattern PATTERN = Pattern.compile(REG); public static void main(String[] args) < String pass /cdn-cgi/l/email-protection" data-cfemail="685b26281a3d3c585a59">[email protected]"; if (PATTERN.matcher(pass).matches()) < System.out.print("The Password " + pass + " is valid"+"\n"); >else < System.out.print("The Password " + pass + " is invalid"+"\n"); >> >
After running this code with content in the “pass” variable, it will print the statement in the output stating whether the password is valid or invalid.
And so one can change the value of the “pass” variable to check for a lot of variation to try and validate the password.
Output: Valid Password:
compile:
run:
The Password [email protected] is valid
BUILD SUCCESSFUL (total time: 1 second)
Output: Invalid Password:
compile:
run:
The Password [email protected] 021 is invalid
BUILD SUCCESSFUL (total time: 1 second)
I hope this tutorial was helpful to you. Thank you.
Validate password in java
In this post, we will see how to validate a password in java.
Here are rules for password:
- Must have at least one numeric character
- Must have at least one lowercase character
- Must have at least one uppercase character
- Must have at least one special symbol among @#$%
- Password length should be between 8 and 20
Using regex
Here is standard regex for validating password.
Here is explanation for above regex
^ asserts position at start of a line
Group (?=.*\\d)
Assert that the Regex below matches
.* matches any character (except for line terminators)
\\ matches the character \ literally (case sensitive)
d matches the character d literally (case sensitive)
Group (?=.*[a-z])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [a-z]
a-z a single character in the range between a (index 97) and z (index 122) (case sensitive)
Group (?=.*[A-Z])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [A-Z]
A-Z a single character in the range between A (index 65) and Z (index 90) (case sensitive)
Group (?=.*[@#$%])
Assert that the Regex below matches
.* matches any character (except for line terminators)
Match a single character present in the list below [@#$%]
@#$% matches a single character in the list @#$% (case sensitive)
. matches any character (except for line terminators)
Quantifier — Matches between 8 and 20 times, as many times as possible, giving back as needed (greedy)
$ asserts position at the end of a line
Here is java program to implement it.