Converting bullet point list to checkboxes once requirements have been satisfied

I am working on developing a password validator with specific regex conditions in Material UI that transitions from bullet points to checkboxes when the criteria are satisfied.

Initially, I attempted to use the npm library NiceInputPassword, but it did not allow me to easily update the state. As a result, I have decided to revert back to using regular Material UI components. Although I have researched documentation on lists in Material UI, I have not found any information on how to convert bullet points to checkboxes like shown in the provided image.

Answer №1

If you want to fulfill all your needs, utilize the @mui/material and @mui/icons-material libraries in this manner:

import { TextField } from "@mui/material";
import { useEffect, useState } from "react";
import "./styles.css";
import CheckCircleIcon from "@mui/icons-material/CheckCircle";
import CircleIcon from "@mui/icons-material/Circle";

function checkUppercase(str) {
  for (let i = 0; i < str.length; i++) {
    if (
      str.charAt(i) === str.charAt(i).toUpperCase() &&
      str.charAt(i).match(/[a-z]/i)
    ) {
      return true;
    }
  }
  return false;
}

const SPECIAL_CHARS = "!@#$%^&*()";

function checkSpecialChars(str) {
  const alreadyFoundChars = [];
  for (let i = 0; i < str.length; i++) {
    const currentChar = str[i];
    if (!alreadyFoundChars.includes(currentChar)) {
      if (SPECIAL_CHARS.includes(currentChar)) {
        alreadyFoundChars.push(currentChar);
      }
    }
  }
  return alreadyFoundChars.length >= 3;
}

const getIcon = (isChecked) => {
  const smallDotIcon = <CircleIcon sx={{ fontSize: "0.4rem" }} />;
  const checkCircleIcon = <CheckCircleIcon sx={{ fontSize: "0.8rem" }} />;
  const iconToBeRendered = isChecked ? checkCircleIcon : smallDotIcon;

  return (
    <div
      style={{
        height: "20px",
        width: "15px",
        display: "flex",
        alignItems: "center",
        justifyContent: "center"
      }}
    >
      {iconToBeRendered}
    </div>
  );
};

const prepareHelperText = (value) => {
  const firstIcon = getIcon(value.length >= 8);
  const secondIcon = getIcon(checkUppercase(value));
  const thirdIcon = getIcon(checkSpecialChars(value));

  return (
    <div>
      <div style={{ display: "flex" }}>
        {firstIcon}
        Must contain at least 8 characters
      </div>
      <div style={{ display: "flex" }}>
        {secondIcon} Must contain at least 1 uppercase letter
      </div>
      <div style={{ display: "flex" }}>
        {thirdIcon} Must contain 3 of the 4 types of characters !@#$%^&*()
      </div>
    </div>
  );
};

export default function App() {
  const [value, setValue] = useState("");
  const [helperText, setHelperText] = useState("");

  useEffect(() => {
    setHelperText(prepareHelperText(value));
  }, [value]);

  return (
    <div className="App">
      <TextField
        type="password"
        label="Password"
        value={value}
        onChange={(e) => setValue(e.target.value)}
        helperText={helperText}
        sx={{
          "& .Mui-focused": {
            color: "purple"
          },
          "& label.Mui-focused": {
            color: "purple !important"
          },
          "& .MuiOutlinedInput-root": {
            "&.Mui-focused fieldset": {
              borderColor: "purple"
            }
          }
        }}
      />
    </div>
  );
}

To see a demonstration of this solution in action, visit this sandbox.

Answer №2

To achieve your desired outcome using the available libraries and components, there are a few steps involved which I will explain in detail.

When working with React-Nice-Input-Password, you can provide a custom class name for different states such as success by utilizing

<NiceInputPassword successClassName="custom-success"
. By adding this prop, you can style the bullet points accordingly using CSS selectors like
.input-password__description li.custom-success:before
. Consider experimenting with less specific selectors for customization possibilities.

The interesting part comes when styling the bullet points. You can set the background-color: transparent, then add a background image using a Data URL referencing an SVG code like the CheckCircle from MUI Icons with customized properties such as width, height, and fill color.

.input-password__description li.custom-success:before {
  background-color: transparent;
  background-image: url('data:image/svg+xml;utf-8,<svg xmlns="http://www.w3.org/2000/svg" width="10" height="10" viewBox="0 0 24 24"><path fill="%232196F3" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"></path></svg>');
}

If you wish to customize the color further, you have options like adjusting the fill property or using the filter CSS property to modify specific elements.

Remember to import the CSS file appropriately into your project for the styles to take effect, like import './custom.css';.

For reference, here is a sandbox showcasing the described changes in action with varying colors for the success bullet points:

https://codesandbox.io/s/reactniceinputpassword-forked-od5r1y?fontsize=14&hidenavigation=1&theme=dark

Additional resources for further reading:

  • Guide on changing SVG fill color in base-64 background image data
  • Using Material Design Icon as CSS background-image value

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

Rotating elements in CSS using the transform property with rotateX and rotateY values

I've created a transformation effect using CSS, and now I'm looking to start with a specific rotation (rotateX(15deg) rotateY(180deg)) and then animate it back to its original position. Is there a way to achieve this reversal effect and how can i ...

What is the best way to render images on the server side in React?

I've got this snippet of code residing in my server/server.js import path from 'path'; import fs from 'fs'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import express from 'ex ...

Guide on decrypting a file encrypted with C# using Node JS

I currently have encrypted files in C# using DES and PKCS7 encryption. My objective is to decrypt these files in Node JS. The decryption code in C# that I am using appears like this: public string SSFile_Reader( string fileToDecrypt ) { DESCryptoService ...

The jQuery onchange function does not have the ability to limit the input to only

When using the script to sum the input value, everything seems to be working fine. However, I am facing an issue where clicking up and down on the "input#total_selfmark" does not change the value. Additionally, when I manually type in a number, the "input# ...

Encountering a getStaticProps error while using Typescript with Next.js

I encountered an issue with the following code snippet: export const getStaticProps: GetStaticProps<HomeProps> = async () => { const firstCategory = 0; const { data }: AxiosResponse<MenuItem[]> = await axios.post( ...

Troubleshooting ng-class functionality in AngularJS

I am attempting to utilize AngularJS in order to change the class name of a div element. Despite following the guidance provided in this answer, I am encountering difficulties as the class name is not updating in my view. Below is the code from my view: ...

"Dynamically moving" background on canvas

Struggling to animate a dynamic "background" for my canvas project using raphaelJS. Here's the code snippet I'm working with: function bg(){ h = 0; var terra = paper.rect(0, 500 + h, 900, 100); terra.attr({'fill': '# ...

Executing npm commands within a complex folder hierarchy

I am facing an issue where I can only execute my npm scripts like npm run dev or npm run build when my folder is placed on the Desktop. However, when I try to move the folder into my directory structure, it throws the following error: npm run dev > &l ...

Using an Ajax call within an event handler function

After spending a full day attempting to execute an AJAX call within an event handler function, I've tried various combinations of when(), then(), and done(), as well as setting async: false. However, I keep encountering undefined errors despite my eff ...

Unit testing controllers in AngularJS with Karma often involves setting up mock services to simulate dependencies

Currently, I am immersed in the development of a Single Page Application using AngularJS as part of my Treehouse Full Stack JavaScript TechDegree. My main focus right now is on conducting unit tests for the controllers. The challenge lies in testing contro ...

What is the best way to choose the member variables in this specific data structure?

I have been assigned the task of retrieving the cities from various countries, but I am unsure of the best approach to do so. How can I easily extract city names like: For example, for USA it would be NYC and SFO. I attempted using the code snippet cityD ...

What is the method for incorporating a checkmark symbol into a chosen MUI React ToggleButton?

Can anyone help me with a simple question? I am trying to figure out how to add a check icon inside the selected ToggleButton. Unfortunately, Stack Overflow won't allow me to post my question in detail. Any explanations would be greatly appreciated! e ...

What is the best way to distribute components with varying cell heights?

I am currently working on creating a user interface layout with components that need to be arranged in a specific order, as depicted in the accompanying image. My task involves developing a Material UI Dialog within a React application based on the design ...

How can I pass props from a page to components in Next.js using getServerSideProps?

Struggling to fetch the coingecko-api for accessing live bitcoin prices. Trying to pass return props of getServerSideProps to my <CalculatorBuy /> component within the <Main /> component. Facing issues when importing async function in calcula ...

Is there a method for enabling GPT-3's "davinci" to engage in conversation with users via a bot on Discord by utilizing discord.js?

var collector = new MessageCollector(message.channel, filter, { max: 10, time: 60000, }) start_sequence = "\nAI: " retart_sequence = "\nHuman: " collector.on("collect", (msg) => { ...

How can you display or conceal an HTML page in Jquery Mobile?

This code snippet is used for toggling the visibility of a div. $("[id*=viewMeButton]").click(function(){ $("[id*=viewMe]").toggle(); $("[id*=viewMeButton]").show(); }); In Jquery Mobile, similar functionality can be implemented to show/hide a ...

Implementing a soft transition to intl-tel-input plugin

This tel-input plugin was developed by Jack O'Connor. You can find the plugin here: https://github.com/Bluefieldscom/intl-tel-input I have observed that the flags take approximately one second to download, and I would like to enhance this process wi ...

Executing a Node.js program using the command line without having to type out the word 'node'

I am currently working on a Node.js package that includes a command-line utility. Right now, alacon.js is situated in the root of the package. To execute this utility, I have to use the word node followed by the utility's name, like so: node alacon ...

Issue with undefined arrays in the Angular merge sort visualization tool

I am currently working on developing a visualizer for sorting algorithms using Angular. However, I have encountered some difficulties while implementing merge sort. As a Java programmer, I suspect that there may be an issue with my TypeScript code and the ...

Why is it that the condition of being undefined or not functioning properly in state?

I am currently facing an issue with a piece of code I wrote in React JS. The state variable is not functioning as expected and even after modifying it upon button click, nothing seems to be working. After checking the console, I noticed that the state rema ...