GithubHelp home page GithubHelp logo

tarunbatra / password-validator Goto Github PK

View Code? Open in Web Editor NEW
283.0 5.0 41.0 1.12 MB

Validates password according to flexible and intuitive specification

Home Page: https://www.npmjs.com/package/password-validator

License: MIT License

JavaScript 100.00%
password validate schema validation password-validator validation-library npm nodejs

password-validator's Introduction

logo

npm version npm downloads gh action build status coverage status

Install

npm install password-validator

Usage

var passwordValidator = require('password-validator');

// Create a schema
var schema = new passwordValidator();

// Add properties to it
schema
.is().min(8)                                    // Minimum length 8
.is().max(100)                                  // Maximum length 100
.has().uppercase()                              // Must have uppercase letters
.has().lowercase()                              // Must have lowercase letters
.has().digits(2)                                // Must have at least 2 digits
.has().not().spaces()                           // Should not have spaces
.is().not().oneOf(['Passw0rd', 'Password123']); // Blacklist these values

// Validate against a password string
console.log(schema.validate('validPASS123'));
// => true
console.log(schema.validate('invalidPASS'));
// => false

// Get a full list of rules which failed
console.log(schema.validate('joke', { list: true }));
// => [ 'min', 'uppercase', 'digits' ]

Advanced usage

Details about failed validations

Sometimes just knowing that the password validation failed or what failed is not enough and it is important to get more context. In those cases the details option can be used to get more details about what failed.

console.log(schema.validate('joke', { details: true }));

The above code will output:

[
  {
    validation: 'min',
    arguments: 8,
    message: 'The string should have a minimum length of 8 characters'
  },
  {
    validation: 'uppercase',
    message: 'The string should have a minimum of 1 uppercase letter'
  },
  {
    validation: 'digits',
    arguments: 2,
    message: 'The string should have a minimum of 2 digits'
  }
]

Custom validation messages

The validation messages can be overriden by providing a description of the validation. For example:

schema.not().uppercase(8, 'maximum 8 chars in CAPS please')

The above validation, on failure, should return the following object:

  {
    validation: 'min',
    arguments: 8,
    inverted: true,
    message: 'maximum 8 chars in CAPS please'
  },

Plugins

Plugin functions can be added to the password validator schema for custom password validation going beyond the rules provided here. For example:

var validator = require('validator');
var passwordValidator = require('password-validator');

var schema = new passwordValidator()
    .min(3, 'Password too small')
    .usingPlugin(validator.isEmail, 'Password should be an email');

schema.validate('not-an-email', { details: true })
// [{ validation: 'usingPlugin', arguments: [Function: isEmail], message: 'Password should be an email' }]

Rules

Rules supported as of now are:

Rules Descriptions
digits([count], [description]) specifies password must include digits (optionally provide count paramenter to specify at least n digits)
letters([count], [description]) specifies password must include letters (optionally provide count paramenter to specify at least n letters)
lowercase([count], [description]) specifies password must include lowercase letters (optionally provide count paramenter to specify at least n lowercase letters)
uppercase([count], [description]) specifies password must include uppercase letters (optionally provide count paramenter to specify at least n uppercase letters)
symbols([count], [description]) specifies password must include symbols (optionally provide count paramenter to specify at least n symbols)
spaces([count], [description]) specifies password must include spaces (optionally provide count paramenter to specify at least n spaces)
min(len, [description]) specifies minimum length
max(len, [description]) specifies maximum length
oneOf(list) specifies the whitelisted values
not([regex], [description]) inverts the result of validations applied next
is() inverts the effect of not()
has([regex], [description]) inverts the effect of not() and applies a regex (optional)
usingPlugin(fn, [description]) Executes custom function and include its result in password validation

Options

The following options can be passed to validate method:

  • list - If set, the validate method returns a list of rules which failed instead of true/false.

Resources

For APIs of other older versions, head to Wiki.

License

MIT License

password-validator's People

Contributors

aramando avatar dependabot[bot] avatar faxemaxee avatar fersilva16 avatar geoffmschaller avatar gsantiago avatar iulianaturcanu avatar marktlinn avatar pgee70 avatar runhorst avatar tarunbatra avatar thakursaurabh1998 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

password-validator's Issues

parameter to control count of e.g. digits required

Hey,

thanks for the great package, I was wondering what your thoughts are when it comes to enable something like this:

schema.has().digits(3) – which would check if there are at least 3 digits

I think we could achieve this using .has(regex) but this might be a nice addition.

What do you think?

Max

list option - result undefined when no rules are broken

Running the validation with the list parameter set to true, returns undefined when no rules are broken.

In my opinion, you should return an empty array, because this would avoid having to make a double check to verify that the result is not undefined. By doing this, the length begin 0 would immediately confirm that there are no broken rules.

Too much recursion exception is being thrown when a string with 28 characters and more is entred.

Recursion exception is being thrown when a password with 28 characters long has been entered for validation.

Here is a snippet from my code:
const pwordValidator = new passwordValidator();
pwordValidator .has() .digits(Number(minimumNumericCharacters) || defaultMinimumNumericChars); pwordValidator.validate(password);
Here is the exception:
Uncaught (in promise) InternalError: too much recursion _process lib.js:13 digits lib.js:80 _isPasswordValidFor index.js:26 validate index.js:81 isPasswordValid UserAccounts.tsx:314

TypeScript types

Hi,

Are there any typescript types available for this project?

Thanks.

Trouble in Angular6 project with Typescript

I'm sure i'm doing something dumb but I'm trying to use this in my project and I'm having trouble getting it to work. It says it can't find a declaration file and that the index.js file implicitly has an any type. I added this to my tsconfig file "noImplicitAny": false, but it's still giving me this warning. I'm importing it in my component like this: import * as PasswordValidator from '../../../node_modules/password-validator';. I've also tried it like this: import { PasswordValidator } from '../../../node_modules/password-validator';.

When I console log schema it gives me this error message..
ERROR TypeError: Cannot read property 'is' of undefined at AccountFormComponent.push../src/app/account-form/account-form.component.ts.AccountFormComponent.validatePassword (account-form.component.ts:67) at Object.eval [as updateRenderer] (AccountFormComponent.html:69) at Object.debugUpdateRenderer [as updateRenderer] (core.js:10879) at checkAndUpdateView (core.js:10255) at callViewAction (core.js:10491) at execComponentViewsAction (core.js:10433) at checkAndUpdateView (core.js:10256) at callViewAction (core.js:10491) at execEmbeddedViewsAction (core.js:10454) at checkAndUpdateView (core.js:10251)

I'm just using the example code in your README. Not sure where to go from here. Thanks

What about add a validation rule for repeating chars?

Hi,
first of all thanks for this module, really useful and easy to use.

Have you any plan to add an extra validation rule, to check if the password contains a character repeated more than X time?

Thanks, cheers.
Fabio

Add or(...)?

Any thoughts on adding an .or() operation?

I would like to specify something like:

min 8, max 100
Use a capitol letter, a lower case letter, and a symbol
OR
use spaces and minimum length 15

Clearly this could be done by having separate logic based on an if in my code... but I think it'd be cleaner to have it in the library.

Return the first failed validation

Right now, there are two modes of using the library:

  • Return boolean on validations (returns false on first failed validation)
  • Return list of all failed validations (iterate through all the failed validations)

We should also have a mode where no further validations are matched if one fails, but also get which one failed.

Version 5.2.0 typings/index.d.ts

It seems like version 5.2.0 added details to the validate options but the change is not reflected in the typings/index.d.ts file?

Syntax error in IE11

The module exposes ES6 which does not work in IE11, resulting in a syntax error

Solution: Transpile the module to ES5

Produce specific error messages

Let's say my schema looks like this:

const passwordSchema = new PasswordValidator()
  .is().min(8)
  .is().max(32)
  .has().letters()
  .has().digits();

Now when i validate a given password, the only thing I get in return is an array of rule names, like this:

const errors = passwordSchema.validate('short', { list: true });
// => ['min', 'digits']

It would be better to return specific error message, like the following:

const errors = passwordSchema.validate('short', { list: true });
// => ['Must have a minimum length of 8!', 'Must contain digits!']

Or, to make it less opinionated, just return the method name with the specified parameter, so I can create custom error messages:

const errors = passwordSchema.validate('short', { list: true });
// => [ { method: 'min', arg: 8 }, { method: 'digits' } ]
//        Minimum length of 8        Must contain digits

Plugin system

The library provides an API to maintain password validations easily and is objective in nature. However real life problems require subjectivity, like the problem of password strength is solved wonderfully by zxcvbn.

Till now I have been of the opinion that subjectivity should remain in the user-land. However it is cumbersome for the application developer to use multiple incoherent libraries to achieve a password policy which is in the best interest of the users' security.

An interesting proposition of a plugin system has come forward to solve this problem during an offline discussion with @pgAdmin. Prima facie, a plugin system will make it easier to make subjective password policies without bloating the library and helping the developer manage and customize password policies using the library's well structured API.

I'm creating this issue as a place to discuss and will add more thoughts later.

Not working IE 11, giving SCRIPT1002 Syntex error

Hi,
I am using password-validator for my react project.
I custom created the initial setup using babel + webpack without using the create-react-app.

ISSUE: When I run the project on IE 11 app it throws a SCRIPT1002 Syntex error.

I am using react polyfills but still, it is giving me the same error.

If I remove password-validator package it works fine.

The Error
Image of Error
Image of Error

My package JSON file.

{
  "name": "example",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "cross-env NODE_ENV=development webpack-dev-server --open --env.dev --config webpack.dev.js",
    "build": "cross-env NODE_ENV=production webpack --env.prod --config webpack.prod.js",
    "lint": "./node_modules/.bin/eslint --ext .js,.jsx './' --ignore-path .gitignore",
    "install:clean": "rm -rf node_modules/ && rm -rf yarn.lock && yarn install && yarn start"
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "*.{js,jsx}": "npm run lint"
  },
  "license": "MIT",
  "devDependencies": {
    "@babel/core": "^7.9.0",
    "@babel/plugin-proposal-class-properties": "^7.8.3",
    "@babel/preset-env": "^7.9.0",
    "@babel/preset-react": "^7.9.4",
    "autoprefixer": "^9.7.5",
    "babel-eslint": "^10.1.0",
    "babel-loader": "^8.1.0",
    "cross-env": "^7.0.2",
    "css-loader": "^3.4.2",
    "cssnano": "^4.1.10",
    "dotenv-flow-webpack": "^1.0.0",
    "eslint": "^6.8.0",
    "eslint-config-airbnb": "^18.1.0",
    "eslint-config-node": "^4.0.0",
    "eslint-config-prettier": "^6.10.1",
    "eslint-plugin-import": "^2.20.1",
    "eslint-plugin-jsx-a11y": "^6.2.3",
    "eslint-plugin-node": "^11.0.0",
    "eslint-plugin-prettier": "^3.1.2",
    "eslint-plugin-react": "^7.19.0",
    "file-loader": "^6.0.0",
    "husky": "^4.2.3",
    "less": "^3.11.1",
    "less-loader": "^5.0.0",
    "lint-staged": "^10.0.9",
    "node-sass": "^4.13.1",
    "postcss-cssnext": "^3.1.0",
    "postcss-import": "^12.0.1",
    "postcss-loader": "^3.0.0",
    "prettier": "^2.0.2",
    "react-svg-loader": "^3.0.3",
    "sass-loader": "^8.0.2",
    "style-loader": "^1.1.3",
    "webpack": "^4.42.1",
    "webpack-cli": "^3.3.11",
    "webpack-dev-server": "^3.10.3"
  },
  "dependencies": {
    "@fortawesome/fontawesome-svg-core": "^1.2.28",
    "@fortawesome/free-regular-svg-icons": "^5.13.0",
    "@fortawesome/free-solid-svg-icons": "^5.13.0",
    "@fortawesome/react-fontawesome": "^0.1.9",
    "antd": "^4.1.0",
    "axios": "^0.19.2",
    "browserslist": "^4.14.0",
    "classnames": "^2.2.6",
    "clean-webpack-plugin": "^3.0.0",
    "echarts": "^4.7.0",
    "echarts-for-react": "^2.0.15-beta.1",
    "echarts-stat": "^1.1.1",
    "html-webpack-plugin": "^4.0.2",
    "lodash.isempty": "^4.4.0",
    "lodash.isequal": "^4.5.0",
    "lodash.merge": "^4.6.2",
    "lodash.mergewith": "^4.6.2",
    "mini-css-extract-plugin": "^0.9.0",
    "moment": "^2.24.0",
    "password-validator": "^5.0.3",
    "prop-types": "^15.7.2",
    "qs": "^6.9.3",
    "react": "^16.13.1",
    "react-app-polyfill": "^1.0.6",
    "react-dom": "^16.13.1",
    "react-full-screen": "^0.2.4",
    "react-redux": "^7.2.0",
    "react-resizable": "^1.10.1",
    "react-router-dom": "^5.1.2",
    "react-scrollbars-custom": "^4.0.25",
    "redux": "^4.0.5",
    "redux-devtools-extension": "^2.13.8",
    "redux-thunk": "^2.3.0",
    "sass": "^1.26.3",
    "webpack-merge": "^4.2.2"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version",
      "ie 11"
    ]
  }
}

Respect non-english upper and lowercase letters

let passwordValidator = require("password-validator");

// Create a schema
let schema = new passwordValidator();

// Add properties to it
schema
  .has()
  .uppercase()
  .has()
  .lowercase();

console.log(schema.validate("ÅÄÖåäö"));

expected output: true
received output: false

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.