Home >Java >javaTutorial >How Can I Improve My Java Password Validation Regex to Reject Whitespace?

How Can I Improve My Java Password Validation Regex to Reject Whitespace?

Barbara Streisand
Barbara StreisandOriginal
2024-12-11 00:19:11687browse

How Can I Improve My Java Password Validation Regex to Reject Whitespace?

Regular Expression for Password Validation in Java

To validate passwords in a Java application, a custom regular expression (regexp) can be defined as a configuration parameter.

Problem:

The regexp:

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

enforces password rules such as minimum length, presence of digits, lowercase and uppercase letters, and special characters. However, it lacks support for identifying passwords without spaces, tabs, or carriage returns.

Solution:

To address this issue, append the following to the existing regexp:

(?=\S+$)

Final Regular Expression:

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

Explanation:

  • ^ and $ are anchors that match the start and end of the string, ensuring the entire password is validated.
  • (?=.*[0-9]) asserts the presence of at least one digit.
  • (?=.*[a-z]) asserts the presence of at least one lowercase letter.
  • (?=.*[A-Z]) asserts the presence of at least one uppercase letter.
  • (?=.*[@#$%^& =]) asserts the presence of at least one special character (@#%$^ etc.).
  • (?=S $) asserts the absence of spaces, tabs, carriage returns, or any whitespace characters.
  • .({8,}$ matches any character (.) occurring at least eight times, ensuring the password meets the minimum length requirement.

The above is the detailed content of How Can I Improve My Java Password Validation Regex to Reject Whitespace?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn