Quantcast
Channel: Baeldung
Viewing all articles
Browse latest Browse all 3522

Regular Expression for Password Validation in Java

$
0
0

1. Introduction

Regarding cybersecurity, password validation is essential in protecting users’ accounts. Moreover, using regular expressions (regex) in Java provides a powerful and dynamic way of imposing specific standards for password complexity.

In this tutorial, we’ll delve into utilizing the regex for Java-based password validation processes.

2. Criteria for a Robust Password

Before we get into the code, we’ll establish what makes a strong password. An ideal password should:

  • Have eight characters or more
  • Include a capital letter
  • Use at least one lowercase letter
  • Consists of at least one digit
  • Need to have one special symbol (i.e., @, #, $, %, etc.)
  • Doesn’t contain space, tab, etc.

3. Implementation in Java

3.1. Regular Expression-based Password Validation

Regular expressions, or regex, are useful tools in Java that allow searching, matching, and transforming strings based on certain patterns. In the same context, regex adopts a more static approach for password validation that operates with the help of predefined regular expressions.

The following Java regular expression encapsulates the specified requirements:

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

Breaking down its components:

  • ^: indicates the string’s beginning
  • (?=.*[a-z]): makes sure that there is at least one small letter
  • (?=.*[A-Z]): needs at least one capital letter
  • (?=.*\\d): requires at least one digit
  • (?=.*[@#$%^&+=]): provides a guarantee of at least one special symbol
  • .{8,20}: imposes the minimum length of 8 characters and the maximum length of 20 characters
  • $: terminates the string

Let’s use regex for password validation:

@Test
public void givenStringPassword_whenUsingRegulaExpressions_thenCheckIfPasswordValid() {
    String regExpn = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=])(?=\\S+$).{8,20}$";
    Pattern pattern = Pattern.compile(regExpn, Pattern.CASE_INSENSITIVE);
    Matcher matcher = pattern.matcher(password);
    assertTrue(matcher.matches());
}

Here, we characterize the regExpn regular expression, which specifies certain rules for a password. Besides, we compile the regExpn regular expression into a pattern using Pattern.compile() method and then create a matcher for the given password through the pattern.matcher() method.

Lastly, we utilize the matcher.matches() method to determine if the password meets the regExpn regular expression.

3.2. Dynamic Password Validation

This approach presents a dynamic password verification method that enables the creation of a pattern based on different attributes. This technique involves an arbitrary pattern, including a minimum/maximum length, special symbols, and other elements.

Let’s implement this approach:

@Test
public void givenStringPassword_whenUsingDynamicPasswordValidationRules_thenCheckIfPasswordValid() {
    boolean result = false;
    try {
        if (password != null) {
            String MIN_LENGTH = "8";
            String MAX_LENGTH = "20";
            boolean SPECIAL_CHAR_NEEDED = false;
            String ONE_DIGIT = "(?=.*[0-9])";
            String LOWER_CASE = "(?=.*[a-z])";
            String UPPER_CASE = "(?=.*[A-Z])";
            String SPECIAL_CHAR = SPECIAL_CHAR_NEEDED ? "(?=.*[@#$%^&+=])" : "";
            String NO_SPACE = "(?=\\S+$)";
            String MIN_MAX_CHAR = ".{" + MIN_LENGTH + "," + MAX_LENGTH + "}";
            String PATTERN = ONE_DIGIT + LOWER_CASE + UPPER_CASE + SPECIAL_CHAR + NO_SPACE + MIN_MAX_CHAR;
            assertTrue(password.matches(PATTERN));
        }
    } catch (Exception ex) {
        ex.printStackTrace();
        fail("Exception occurred: " + ex.getMessage());
    }
}

Here, we first ensure that the password doesn’t equal null before carrying on with validation. Then, the method determines validation criteria through individual strings, stipulating such issues as the presence of one digit, one lower case symbol, and an upper case letter with optionally special characters.

Moreover, we use the MIN_MAX_CHAR string to establish the password’s minimum and maximum length limits, using defined standards MIN_LENGTH and MAX_LENGTH. Afterward, the composite PATTERN string concatenates all the indicated prerequisites to develop a dynamic validation pattern.

Finally, we utilize the assertTrue(password.matches(PATTERN)) method to verify the password’s compliance with the dynamically created pattern. If exceptions occur during validation, the test is considered failed; details of the exception are printed for debugging purposes.

This approach provides the flexibility to set password validation rules by changing parameters, which makes it appropriate for different validators.

4. Conclusion

In summary, Java regular expressions are a reliable mechanism for performing text validation and manipulation, particularly when it involves the application of strong password security.

Hence, in this article, we give a concise step-by-step guide for constructing an appropriate regular expression to validate passwords, providing the foundation for alteration that can increase safety during user account creation.

As always, the complete code samples for this article can be found over on GitHub.

       

Viewing all articles
Browse latest Browse all 3522

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>