Continuing to fine-tune the regular expression for password validation

How can we refine this regular expression to only include alphanumeric characters?

I assumed that by requiring at least 2 uppercase letters, lowercase letters, and digits, the expression would limit itself to those specific types of characters. Unfortunately, it still allows undesirable characters like tildes.

/^[\s]*((?=([^\s]*\d){2,})(?=([^\s]*[a-z]){2,})(?=([^\s]*[A-Z]){2,})[^\s]{8,16})[\s]*$/

Answer №1

It seems like using a single regular expression to differentiate between uppercase and lowercase letters as well as digits is not possible. In the world of regex, counting can be quite challenging.

Therefore, I believe the solution will involve using a regex to identify the specific types of characters present, followed by a separate step to count the uppercase characters:

/[A-Za-z0-9]{8,16}/

To validate that the string contains at least two uppercase letters, two lowercase letters, and two digits, you can use these three regex patterns:

/[A-Z].*[A-Z]/
/[0-9].*[0-9]/
/[a-z].*[a-z]/

If a string matches all four of these regex patterns, it will meet the criteria for your password requirements.

Alternatively, you may find it simpler to create a function that counts characters in a loop instead of relying on regexes.

By the way, if you're looking for different ways to construct a regex, a helpful resource is

Answer №2

Check out this method using just a few needles. fiddle

alert( validate('AbcdeFghij123') );
alert( validate('Abcdeghij123') ); // Only 1 capital
alert( validate('AbcdeFghij') ); // No numbers
alert( validate('ABCDEF123') ); // No lowercase
alert( validate('Abc~~ghij123') ); // Tilde
alert( validate('') ); // Blank

function validate(password) {
    return /^[A-Za-z0-9]+$/.test(password)
        && /[A-Z][^A-Z]*[A-Z]/.test(password)
        && /[a-z][^a-z]*[a-z]/.test(password)
        && /[0-9][^0-9]*[0-9]/.test(password);
}

If you want to restrict the length to be between X and Y, replace /^[A-Za-z0-9]+$/ with /^[A-Za-z0-9]{X,Y}$/. Pretty easy, right?

Answer №3

Check out this function that can verify a password based on specific criteria:

/* Validate a password with the following requirements:
    * Must contain 8 to 16 letters and digits.
    * Can have optional leading and trailing whitespace.
    * Should have at least 2 uppercase letters.
    * Should have at least 2 lowercase letters.
    * Should have at least 2 decimal digits.
    The regex in (PHP) free-spacing mode with comments is provided below:
    $re = '/# Validate password has 2 upper, 2 lower and 2 digits.
        ^                        # Anchor to start of string.
        (?=(?:[^A-Z]*[A-Z]){2})  # Assert 2 uppercase letters.
        (?=(?:[^a-z]*[a-z]){2})  # Assert 2 lowercase letters.
        (?=(?:[^0-9]*[0-9]){2})  # Assert 2 decimal digits.
        \s*                      # Allow leading whitespace.
        ([A-Za-z0-9]{8,16})      # $1: Password 8-16 of [A-Za-z0-9]
        \s*                      # Allow trailing whitespace.
        $                        # Anchor to end of string.
        /x';
    If valid password, return password trimmed of leading and trailing whitespace.
    If invalid password, return empty string.
*/
function validatePassword(text)  {
    var re = /^(?=(?:[^A-Z]*[A-Z]){2})(?=(?:[^a-z]*[a-z]){2})(?=(?:[^0-9]*[0-9]){2})\s*([A-Za-z0-9]{8,16})\s*$/;
    var m = text.match(re);
    if (m) return m[1];     // If valid, return trimmed password
    return '';              // If not valid, return empty string
}

Answer №4

It's actually quite straightforward. This method will get the job done.

/^(?=.*[a-z].*[a-z])(?=.*[A-Z].*[A-Z])(?=.*\d.*\d)[a-zA-Z0-9]{8,16}$/

Necessary criteria: 2 numbers, 2 lowercase letters, 2 uppercase letters, at least 8 and maximum of 16 characters in total

Explanation of the answer...

// Ensures presence of 2 lowercase letters (a-z)
(?=.*[a-z].*[a-z])

// Ensures presence of 2 uppercase letters (A-Z)
(?=.*[A-Z].*[A-Z])

// Ensures presence of 2 digits (0-9)
(?=.*\d.*\d)

// Requires all 3 conditions to be met and sets minimum string length of 8 and maximum of 16
[a-zA-Z0-9]{8,16}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having difficulty retrieving items from an array of objects

After making a call to an API, I stored the response in my state array called mydata by pushing each element of the response (which is an array of objects) onto it. state={ mydata:[] } componentDidMount() { const headers = { "Conte ...

Interactive elements within $ionicLoading

I am attempting to create a clickable button within the $ionicLoading template. I need to execute some code when that button is clicked. Unfortunately, it seems like ng-click is not working. Is there a workaround for this issue? Or am I making a critical ...

Regular expressions never fail to capture patterns

Looking for a solution to parse a string that may contain text and a URL separated by whitespace? Here's an example: Hello, World! https://example.com/123456 Hello, World! I attempted to use this regex pattern: ^(.*)\s(https://example\.co ...

The Facebook SDK's function appears to be triggering twice

I am currently in the process of integrating a Facebook login button into my website and have made progress, but I have encountered a problem. The Facebook SDK JavaScript code that I am using is as follows: function statusChangeCallback(response) { ...

Converting a JSON object into an array of objects

I am looking to transform the following JSON structure let data = { item1: [11, 12, 13, 14, 15], item2: [16, 17, 18, 19, 20] } into this specific format using JavaScript's native functionalities of arrays or objects (compatible with all web brow ...

Issue with webpack-dev-server causing it to not reload and build automatically due to configuration error

Currently in my project, I am utilizing the following versions: "webpack": "2.2.1", "webpack-dev-server": "2.4.2" I am looking to create an application that can automatically rebuild when a file is changed using webpack-dev-server live reloading. Within ...

The byte order of integer literals in JavaScript

When writing the following line in Javascript: var n = 0x1234, is it always true that n == 4660? This question could also be phrased as follows: Does 0x1234 represent a series of bytes with 0x12 as the first byte and 0x34 as the last byte? Or does 0x1234 r ...

Angularjs collapsible toggle

I am having trouble launching a simple example of collapse. When I click on the "Toggle collapse" button, nothing happens. There are no errors in the console, but there is one warning in Visual Studio. What could be causing this issue and how can I fix it? ...

What are the steps to organize an array of objects by a specific key?

Experimented with the following approach: if (field == 'age') { if (this.sortedAge) { this.fltUsers.sort(function (a, b) { if (b.totalHours > a.totalHours) { return 1; } }); this ...

Can the Browser Mob Proxy capture network traffic for applications that are running on localhost?

I'm currently working on creating a tool that automatically tracks client-side performance. I recently learned that browsermob proxy combined with selenium can be used to write tests for this purpose. However, I'm curious about the possibility of ...

Is there a way to showcase individual components on a single surface one at a time?

Let me try to explain my issue as clearly as possible! I am currently working on a website using React and Material-UI. On one of my pages, I have a Paper component where I want to display different components that I have created, but only one at a time. ...

What are some effective solutions for resolving design problems in Isotope?

When I append the ajax coding, the data is coming fine. However, when I append this style="position: absolute; left: 468px; top: 0px;" css to the new appended data, it is not working. How can I achieve this? Below is my ajax code. Please provide suggestion ...

JavaScript to resize images before uploading without displaying a preview

I'm searching for a way to prevent the need to upload large or heavy image files. I believe utilizing the HTML5 FileAPI library is the best solution for this task. All necessary features have been implemented (upload, re-ordering, etc.), so now I ju ...

Checking with `validate.js` IF statement

I created a form that includes a hidden field. When the user selects "telephone" using a radio button, an additional field is displayed. For validation purposes, I incorporated validate.js into the form. Everything was functioning correctly until I introd ...

The submission form is being triggered immediately upon the page loading

I have a form on the landing page that sends parameters to Vuex actions. It functions correctly when I click the submit button and redirects me to the next page as expected. However, there seems to be a problem. Whenever I open or refresh the page, the par ...

Using webpack's hash in JavaScript for cache busting

Can someone guide me on adding a hash to my js file name for cache-busting purposes? I've researched online but still uncertain about where to include the [hash] element. Any help would be appreciated. Provided below is a snippet from my webpack.conf ...

Utilizing jQuery to Toggle Visibility of Table Rows on Button Click

I have a unique layout on my page where there are two tables positioned side by side. The table on the left consists of buttons with company names, and the table on the right should display employees associated with each specific company. Upon initially l ...

I am facing an issue in my Nextjs project where the Array Object is not being properly displayed

Hi there! I am new to Nextjs and currently learning. I recently created a component called TeamCard which takes imgSrc, altText, title, designation, and socialProfile as parameters. However, when attempting to display the socialProfile object array using m ...

Guide on changing the font size of a selected tab in material-ui

My requirement specifies that the active tab should be styled with a specific color and font size only. Here is my code snippet: <Tabs value={value} onChange={handleChange} ...

Matching with regex cannot distinguish between values and text

let ProcessValue value = let (|Match|_|) pattern input = let m = Regex.Match(input, pattern) in if m.Success then Some ([ for g in m.Groups -> g.Value ]) else None match value with ...