1.3.1 • Published 2 years ago

@doreentseng/passwd v1.3.1

Weekly downloads
3
License
MIT
Repository
github
Last release
2 years ago

@doreentseng/passwd

Random Password Generator and Validation.

NPM JavaScript Style Guide

Features

Random Password Generator

  • Fixed Length
  • Maximum Length and Minimum Length
  • Custom Characters

Password Validation

  • Validata Empty
  • Validate Length
  • Validate Characters
  • Custom Error Messages

DEMO

Link: https://codesandbox.io/s/random-password-generator-npm-o1253

Install

npm install --save @doreentseng/passwd

Usage

Generation

import React, { useEffect, useState } from 'react';
import { generate } from '@doreentseng/passwd';

const Example = () => {
  const [passwd, setPasswd] = useState('');

  const onClickGenerate = () => {
    setPassword(
      generatePassword({
        uppercase: true, // default is true so this line can be removed
        lowercase: false, // the password will not contain any lowercase
        // numbers: true, // default is true so this line can be removed
        symbols: "_-@!", // custom symbols
        maxLength: 20,
        minLength: 8
      })
    );
  };

  const handleChange = e => {
    const value = e.target.value;
    setPasswd(value);
  }

  return (
    <div>
      <input value={passwd} onChange={handleChange} />
      <br />
      <button onClick={onClickGenerate}>Generate</button>
    </div>
  )
}
export default Example;

Validation

validation({ value, ...rules }); // error codes array: ["101", "103"]
import React, { useEffect, useState } from 'react';
import { generate } from "./password";

const Example {
  const [password, setPassword] = useState("");
  const [error, setError] = useState([]);

  const maxLength = 20;
  const minLength = 8;

  const rules = useMemo(
    () => ({
      uppercase: true, // default is true so this line can be removed
      lowercase: true, // the password will not contain any lowercase
      // numbers: true, // default is true so this line can be removed
      symbols: "_-@!", // custom symbols
      maxLength,
      minLength
    }),
    []
  );

  /** 
   * validation returns error codes, you can edit your error messages
   * e.g. ['101', '103']
   */
  const handleError = (codes) => {
    let errors = [];
    for (let i = 0; i < codes.length; i++) {
      switch (codes[i]) {
        case "101":
          errors.push("Required");
          break;
        case "102":
          if (minLength === maxLength) {
            errors.push(`Must be ${minLength} characters.`);
          } else {
            errors.push(`Must be between ${minLength}~${maxLength} characters.`);
          }
          break;
        case "103":
          errors.push("At least one uppercase.");
          break;
        case "104":
          errors.push("At least one lowercase.");
          break;
        case "105":
          errors.push("At least one number.");
          break;
        case "106":
          errors.push("At least one symbol.");
          break;
        case "107":
          errors.push("No other characters are allowed.");
          break;
        default:
          break;
      }
    }
    return errors;
  };

  useEffect(() => {
    const errorCodes = validate({
      value: password,
      ...rules
    });
    const errorList = handleError(errorCodes);
    setError(errorList);
  }, [password, rules]);

  const handleChange = (e) => {
    const value = e.target.value;
    setPassword(value);
  };

  return (
    <div id="main">
      <h3>Random password generator</h3>
      <ol>
        <li>Must be between 8~20 characters.</li>
        <li>At least one upper-case, one lower-case and one number.</li>
        <li>
          At least one of these special characters: - or _. No other special
          characters are allowed.
        </li>
      </ol>
      <div id="container-passwd">
        <input value={password} onChange={handleChange} />
      </div>
      <p style={{ textAlign: "center" }}>Password length: {password.length}</p>

      {!!error && error.length > 0 ? (
        <ul>
          {error.map((item, i) => (
            <li key={i} style={{ color: "red" }}>
              {item}
            </li>
          ))}
        </ul>
      ) : (
        <p style={{ textAlign: "center", color: "green" }}>OK</p>
      )}
    </div>
  );
}

Props

*Notice! If you use generate() and validate() on the same password, you should make sure their props are the same.

Generator Props

*Notice! If maxLength is the same with minLength, the password will get a fixed length.

NameRequiredDefault ValueTypeDescription
uppercasetrueBoolean/StringBy default true, the password will contain uppercase ABCDEFGHJKLMNPQRZTUVWXYZ (without I, O). If set false, the password will not contain any uppercase character. You can customize it like {uppercase: "ABC"}
lowercasetrueBoolean/StringBy default true, the password will contain lowercase abcdefghijkmnopqrstuvwxyz (without l). If set false, the password will not contain any lowercase character. You can customize it like {lowercase: "abc"}
numberstrueBoolean/StringBy default true, the password will contain numbers 123456789 (without 0). If set false, the password will not contain any number. You can customize it like {numbers: "012"}
symbolstrueBoolean/StringBy default true, the password will contain symbols -_. If set false, the password will not contain any symbol. You can customize it like {symbols: "-_@!"}
maxLengthIntegerThe maximum length of the password. At least 4.
minLengthIntegerThe maximum length of the password. At least 4.

Validation Props

*Notice! Props uppercase, lowercase, numbers and symbols are totally the same as in Generator Props.

NameRequiredDefault ValueTypeDescription
valueStringPassword value.
uppercasetrueBoolean/StringThe same as Generator Props.
lowercasetrueBoolean/StringThe same as Generator Props.
numberstrueBoolean/StringThe same as Generator Props.
symbolstrueBoolean/StringThe same as Generator Props.
maxLengthIntegerThe same as Generator Props.
minLengthIntegerThe same as Generator Props.

Validation Error Codes

CodeDescription
101The password is required.
102Length does not match.
103Uppercase does not match.
104Lowercase does not match.
105Numbers does not match.
106Symbols does not match.
107Other characters are not allowed.

License

MIT ©


This hook is created using create-react-hook.

1.3.1

2 years ago

1.3.0

2 years ago

1.2.9

4 years ago

1.2.8

4 years ago

1.2.0

4 years ago

1.1.1

4 years ago

1.1.0

4 years ago

1.2.7

4 years ago

1.2.6

4 years ago

1.2.5

4 years ago

1.2.4

4 years ago

1.2.3

4 years ago

1.2.2

4 years ago

1.2.1

4 years ago

1.1.2

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago