ai / nanoid

A tiny (124 bytes), secure, URL-friendly, unique string ID generator for JavaScript

Home Page:https://zelark.github.io/nano-id-cc/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ensure at least 1 symbol and 1 number in id

ericuldall opened this issue · comments

I'm using this library to generate a random password and to meet the requirements it MUST HAVE at least 1 symbol and 1 number. As of now I'm doing it like this:

  const rand = (min, max) => Math.random() * (max - min) + min;
  const symbols = nanoid.customAlphabet('!@#$%^&*-_', rand(1, 3));
  const numbers = nanoid.customAlphabet('0123456789', rand(1, 3));
  return [symbols(), numbers(), nanoid(12)]
    .join('').split('')
    .map(value => ({ value, sort: Math.random() }))
    .sort((a, b) => a.sort - b.sort)
    .map(({ value }) => value)
    .join('');

Is there a built in way to do something like this?

No. You can use your trick or another tool for this case.

We are focusing on simple task to have nano size.