string-validators

Little Javascript / Typescript library for validating format of string like email, url, password...


Keywords
typescipt, vitest, string, validator, email, nodejs
License
MIT
Install
npm install string-validators@1.0.0

Documentation

String-Validators

ForTheBadge built-with-love
Version


Little Javascript / Typescript library for validating format of string like email, url, password...

GitHub release (latest SemVer including pre-releases) GitHub last commit Stargazers Contributors

Forks Issues requests MIT License


Signaler un Bug · Proposer une Feature


Table of Contents
  1. About The Project
  2. Getting Started
  3. Usage
  4. Validators overview
  5. Roadmap
  6. Contributing
  7. License
  8. Connect with me

About The Project

The first goal of this project is to create complete and personalized validation schemes for strings by using native functions as much as possible. This is in order to obtain maximum security and to avoid as much as possible the use of RegEx which would be likely to be subject to ReDOS attacks.

(back to top)

Getting Started

Installation

Use your preferred node package manager.

> pnpm install

Or clone this repository

  • Clone project

    > git clone https://github.com/jdelauney/string-validators.git

    Go to the project directory

    > cd string-validators
  • Install dependencies with npm, pnpm or yarn:

    > pnpm install

(back to top)

Usage

How to check if an email is valid

import {isValidEmail} from "string-validators";

const isValidEmail = isValidEmail('johndoe@mail.com');
// return true

const isValidEmailIncludeDomainBlackList = isValidEmail('johndoe@dodgeit.com', 'pathto/blacklist-domain.csv');
// return false

You'll can find a file with a non-exhaustive email disposable domain list, in the folder files

How to make your on custom string format validation schema

  1. Create test

    • in the __tests__ folder create your spec test and test it with the following command
      > pnpm test:watch src/__tests__/yourTestFile.spec.ts
    • in the __tests__ folder create your unit test
    import { describe, expect, test } from 'vitest';
    import { stringValidator } from 'string-validators';
    
    const validPasswords = [
      'abC$123DEf',
      'ABc1$ef#gh',
      'aB$C23dE2f',
    ];
    
    const invalidPasswords = [
      '',
      'abcdef',
      'ab$12AB',
      'Ab1$2cdef',
      'AB1$cdef',
    ];
    
    describe('Feature : Strong password validator', () => {
      describe('Given a list of valid password', () => {
        test.each(validPasswords)('When %p as argument, it should return TRUE', async password => {
          const isValid = await isValidEmail(email, '../files/email_disposable.csv');
          expect(isValid).toBe(true);
        });
      });
    
      describe('Given a list of invalid password', () => {
        test.each(invalidPasswords)('When %p as argument, it should return FALSE', async password => {
          const isValid = await isValidEmail(email, '../files/email_disposable.csv');
          expect(isValid).toBe(false);
        });
      });
    });
  2. Launch test in watch mode

> pnpm test:watch src/__tests__/yourTestFile.test.ts
  1. Write your code and refactor it until all tests are green
import {
  stringValidator, 
  isMinLength, 
  isContainsOneOfCharsCount, 
  CHARSET_LOWER_ALPHA, 
  CHARSET_NUMBER, 
  CHARSET_UPPER_ALPHA
} from "string-validators";

const isValidStrongPassword = stringValidator('abC$123DEf', [
  isNot(isEmpty),
  isMinLength(8),
  isContainsOneOfCharsMinCount('$#%+*-=[]/(){}€£!?_', 1),
  isContainsOneOfCharsMinCount(CHARSET_LOWER_ALPHA, 3),
  isContainsOneOfCharsMinCount(CHARSET_UPPER_ALPHA, 2),
  isContainsOneOfCharsMinCount(CHARSET_NUMBER, 2),
]);
// return true

const isValidStrongPassword2 = stringValidator('abC$123Def', [
  isNot(isEmpty),
  isMinLength(10),
  isContainsOneOfCharsMinCount('$#%+*-=[]/(){}€£!?_', 2),
  isContainsOneOfCharsMinCount(CHARSET_LOWER_ALPHA, 3),
  isContainsOneOfCharsMinCount(CHARSET_UPPER_ALPHA, 2),
  isContainsOneOfCharsMinCount(CHARSET_NUMBER, 3),
]);
// return false

(back to top)

Validators overview

To help us as much as possible to create validation schemas. The 'String-Validators' library contains more than 50 validation rules that one can apply.

Here are a few available functions :

  • isEmpty() : check if string is empty
  • isMinLength(min) : check if string has a minimum number of characters
  • isMinLength(max) : check if string has a maximum number of characters
  • isEqualLength(equal) : check if string has the exact required number of characters
  • isUpper() : check if string is in upper case only
  • isLower() : check if string is in lower case only
  • isAlpha() : check if string only contain Alpha characters
  • isNumber() : check if string only contain Number characters
  • isStartsWith(startStr) : check if string starts with
  • isEndsWith(startStr) : check if string ends with
  • isMatch(regex) : check if string match with a regex
  • isSurroundBy(leftStr, rightStr) : check if string is surrounded by leftStr and rightStr
  • isLeftOf(searStr, leftStr) : check if the first occurrence of searchStr have leftStr on his left
  • isNot(fn) : Negate the result of an validator

For the complete list of available validator check the validators folder. Names are enough friendly to understand their purposes.

(back to top)

Roadmap

  • Write a full documentation
  • Add common validators
    • Web site Url Validator
    • Url Validator
    • Password validator
    • Credit card validator
    • UUID Validator
    • IP Validator
    • Username Validator
    • Phone validator
  • Add logical AND operator
  • Add logical OR operator
  • Add isPrefixedBy (+ One of, One of Chars) validators
  • ...more validators

See the open issues for a full list of proposed features (and known issues).

(back to top)

Contributing

Contributions are what make the open source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.

If you have a suggestion that would make this better, please fork the repo and create a pull request. You can also simply open an issue with the tag "enhancement". Don't forget to give the project a star! Thanks again!

  1. Fork the Project
  2. Create your Feature Branch (git checkout -b feature/AmazingFeature)
  3. Commit your Changes (git commit -m 'Add some AmazingFeature')
  4. Push to the Branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

(back to top)

License

Distributed under the MIT License.

Copyright 2022 J.DELAUNEY

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

(back to top)

Connect with me:

jeromedelauney jérôme-delauney-802994bb

Project Link: https://github.com/jdelauney/string-validators

(back to top)