javascript: verify the presence of uppercase and lowercase letters

Can the validation of at least 2 lowercase and 2 uppercase letters be implemented when checking the case? Below is the condition I am currently using.

function HasMixedCase(passwd){
    if(passwd.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/))
        return true;
    else
        return false;
}

Example: http://jsfiddle.net/Ku4mg/

Answer №1

Revised to incorporate feedback from plalx's suggestion:

let m;
if( !(m = password.match(/[a-z]/g)) || m.length < 2) return false;
if( !(m = password.match(/[A-Z]/g)) || m.length < 2) return false;
return true;

Attempting to tackle everything in a single regex can lead to complications, often resulting in excessive backtracking.

Likewise, breaking down your code into smaller tasks enhances readability and comprehension.

Answer №2

While @NietTheDarkAbsol's answer provides a valid approach, I recommend avoiding overcomplicating your functions. It's best to split the logic into separate, easier-to-maintain functions.

function analyzeTextCase(text) {
    return {
        uppercase: (text.match(/[a-z]/g) || []).length,
        lowercase: (text.match(/[A-Z]/g) || []).length
    };
}

function checkMixedCase(password) {
    var caseAnalysis = analyzeTextCase(password);

    return caseAnalysis.lowercase >= 2 && caseAnalysis.uppercase >= 2;
}

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

Exploring network connectivity using Node.js

As someone who is just starting out with the node super framework, I'm curious to find out if there's a library or sub framework in Node.js that allows users to ping a server from the frontend of a web app. Ideally, this tool would provide variou ...

Create a jQuery URL within the $.ajax function

Attempting to execute a $.ajax call and send data to a php file. The php file is situated in a component's directory, while the js file is located in the webroot directory. How can the url section of the $.ajax be configured correctly to point to the ...

There seems to be a problem with the sorting functionality on the table in React JS,

My React table is functioning well with all columns except for the country name column. I double-checked the API and everything seems to be in order, but I'm stuck on how to troubleshoot this issue. const Table = () => { const[country, setCount ...

Removing sourceMappingURL from an Angular Universal build: A step-by-step guide

Using this repository as my foundation, I have successfully resolved most of the plugin errors except for one that continues to elude me. It's puzzling because no other plugin anticipates a .map file in an SSR build since it is intended for productio ...

Is the unit-converts npm package compatible with the website https://unpkg.com?

Having issues importing the npm package 'convert-units' using unpkg, I attempted the following method: <script src="unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="02616d6c746770762f776c6b767142302c31 ...

The TypeScript declaration for `gapi.client.storage` is being overlooked

When I call gapi.client.storage.buckets.list(), TypeScript gives me an error saying "Property 'storage' does not exist on type 'typeof client'." This issue is occurring within a Vue.js application where I am utilizing the GAPI library. ...

What could be causing the issue of loading text not appearing in Vue.js?

I have the following code snippet in my application: <div id="app"> <button v-if="!isPrepared && !isLoading" @click="startLoading()">Start Loading</button> <div v-if="isLoading">Lo ...

Create a complete duplicate of a Django model instance, along with all of its associated

I recently started working on a Django and Python3 project, creating a simple blog to test my skills. Within my project, I have defined two models: class Post(models.Model): post_text = models.TextField() post_likes = models.BigIntegerField() post_ ...

Graph only displays data after button is clicked

I have been working on customizing this jsfiddle to display database data. Check it out here: http://jsfiddle.net/jlbriggs/7ntyzo6u/ Using JSON, I am fetching data from my database and editing chart1 to display the database data: var chart, chartOption ...

JavaScript strangeness

I am currently working on a dynamic page loaded with ajax. Here is the code that the ' $.get' jQuery function calls (located in an external HTML page): <script type="text/javascript"> $(function() { $('button').sb_animateBut ...

Unexpected firing of jQuery blur event upon page load rather than during the expected time

Currently, I am working on a project that involves form validation using jQuery. One element I am focusing on is the email field, where users will input their emails. I want to ensure that the email input is checked once it has been filled out. My initial ...

Validating a particular value using Regex in React Formik

First, I need to ensure that the field is validated for any characters not included in this set: /[ùûüÿ€’“”«»–àâæçéèêëïîôœ]/. If a user enters a character outside of this set, I want Yup to trigger an error message. Secondly, I ...

Guide for creating a scroll-triggered rotation animation using only JavaScript

Looking to achieve a cool scroll effect with an image that rotates on the X-axis by a specific degree, such as 70deg. The goal is to have the image's rotateX value change to 0deg when it enters the viewport upon scrolling and revert back to 70deg whe ...

Ensuring the authenticity of dynamic forms

jQuery(document).ready(function(){ $("#submitButton").click(function () { if ( $("#formToSubmit").validationEngine('validate') == true) { $("#formToSubmit").submit(); } }); Utilizing the Validation Engine plugin for jQuery to valida ...

What is the best way to include basic static files and HTML together in a NodeJS environment?

I am facing an issue trying to serve an HTML file with its CSS and JS files in NodeJS using express.static(), but unfortunately, it is not working as expected. I have followed the steps shown in several tutorials, but for some reason, the output is not co ...

Adding and removing dynamic fields with Bootstrap functionality

Recently, I've been trying to develop a feature where users can add and remove fields by clicking on a button. However, I've encountered a roadblock in my progress. If you take a look at this CodePen link, you'll see what I have so far. My a ...

Error: guild is not defined | discord.js

Having trouble with a ReferenceError that says guild is not defined? I recently encountered a similar issue with members but managed to fix it by adding a constant. As someone new to javascript and node.js, I could use some assistance. I've even tried ...

Having trouble with the Tap to copy discount code function not working in the Shopify cart drawer?

Our goal is to implement tap to copy functionality for code snippets on our Shopify website. It works seamlessly on the product detail page, but in the cart drawer, it only functions properly after the second page load. https://i.sstatic.net/xzMVY.png ...

Validate if the JSON data array contains any elements

I'm currently working with an ajax code and I need to determine whether the JSON data contains an array or not. However, despite my attempts, I am still receiving incorrect output. $.ajax({ url: url, type: 'POST', da ...

Adjust the href link value when a new option is selected

I currently have a select element displayed below. Next to it, there is a link that sets the eID value to a session value. However, I want this value to be updated dynamically whenever a different eID value is selected from the dropdown. Although I can r ...