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

Overview

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 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 { validator } 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 isValidStrongPassword(password);
          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 isValidStrongPassword(password);
          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 {
  validator, 
  minLength, 
  containsOneOfCharsCount, 
  CHARSET_LOWER_ALPHA, 
  CHARSET_NUMBER, 
  CHARSET_UPPER_ALPHA
} from "string-validators";

const isValidStrongPassword = (password: string) => {
  return validator(password, [
    not(isEmpty),
    minLength(8),
    containsOneOfCharsMinCount('$#%+*-=[]/(){}€£!?_', 1),
    containsOneOfCharsMinCount(CHARSET_LOWER_ALPHA, 3),
    containsOneOfCharsMinCount(CHARSET_UPPER_ALPHA, 2),
    containsOneOfCharsMinCount(CHARSET_NUMBER, 2),
  ]);
}

const isValidStrongPassword2 = validator('abC$123Def', [
  not(isEmpty),
  minLength(10),
  containsOneOfCharsMinCount('$#%+*-=[]/(){}€£!?_', 2),
  containsOneOfCharsMinCount(CHARSET_LOWER_ALPHA, 3),
  containsOneOfCharsMinCount(CHARSET_UPPER_ALPHA, 2),
  containsOneOfCharsMinCount(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 the full list of available validators :

  • isEmpty() : check if string is empty

  • isEqual(equalStr)

  • minLength(min) : check if string has a minimum number of characters

  • minLength(max) : check if string has a maximum number of characters

  • rangeLength(min, max)

  • isLengthEqual(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

  • isAlphaNumeric() : check if string only contain Alpha numerics characters

  • isNumber() : check if string only contain Number characters

  • startsWith(startStr) : check if string starts with

  • startsWithOneOf(string[])

  • startsWithOneOfChars(chars)

  • startsWithSpecialChars()

  • startsWithNumber()

  • startsWithUpperCase()

  • startsWithLowerCase()

  • endsWith(startStr) : check if string ends with

  • endsWithOneOf(string[])

  • endsWithOneOfChars(chars)

  • endsWithSpecialChars()

  • endsWithNumber()

  • endsWithUpperCase()

  • endsWithLowerCase()

  • contains(subStr)

  • containsAt(subStr, pos)

  • containsCount(subStr, count)

  • containsMinCount(subStr, minCount)

  • containsMaxCount(subStr, maxCount)

  • containsRangeCount(subStr, minCount, maxCount)

  • containsOneOf(string[])

  • containsOneOfCount(chars, count)

  • containsOneOfMinCount(chars, minCount)

  • containsOneOfMaxCount(chars, maxCount)

  • containsOneOfRangeCount(chars, minCount, maxCount)

  • containsOneOfChars(chars)

  • containsOneOfCharsCount(chars, count)

  • containsOneOfCharsMinCount(chars, minCount)

  • containsOneOfCharsMaxCount(chars, maxCount)

  • containsOneOfCharsRangeCount(chars, minCount, maxCount)

  • containsOnlyOneOfChars(chars)

  • containSpecialChars()

  • match(regex) : check if string match with a regex

  • surroundBy(leftStr, rightStr) : check if string is surrounded by leftStr and rightStr

  • surroundByOneOf(string[], string[])

  • surroundByOneOfChars(startChars, endChars)

  • surroundByOneOfPairs(string[], string[])

  • leftOf(subStr, leftStr) : check if the first occurrence of subStr have leftStr on his left

  • leftOfOneOf(subStr, string[])

  • leftOfOneOfChars(subStr, chars)

  • rightOf(subStr, leftStr) : check if the first occurrence of subStr have rightStr on his right

  • rightOfOneOf(subStr, string[])

  • rightOfOneOfChars(subStr, chars)

  • followBy(subStr, followByStr)

  • followByOneOf(subStr, string[])

  • followByOneOfChars(subStr, chars)

  • oneOfFollowBy()

  • oneOfCharsFollowByOneOfChars()

  • not(validatorFunc) : Negate the result of a validator

  • or(validatorFuncA, validatorFuncB)

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 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)

You might also like...

Piccloud is a full-stack (Angular & Spring Boot) online image clipboard that lets you share images over the internet by generating a unique URL. Others can access the image via this URL.

Piccloud Piccloud is a full-stack application built with Angular & Spring Boot. It is an online image clipboard that lets you share images over the in

Dec 15, 2022

A JavaScript plugin for entering and validating international telephone numbers

A JavaScript plugin for entering and validating international telephone numbers

International Telephone Input A JavaScript plugin for entering and validating international telephone numbers. It adds a flag dropdown to any input, d

Dec 30, 2022

🌐 Text Input Component for validating and formatting international phone numbers.

🌐  Text Input Component for validating and formatting international phone numbers.

React Native Intl Phone Field Try the Expo Snack 👏 🕹️ Demo It's a javascript-only (no native code) component that can run in iOS, Android, Expo & Re

Jul 8, 2022

An API for producing and validating ActivityPub objects.

ActivityHelper A library that exports an API for producing and validating ActivityPub objects. In a federated system bound together by protocols, it's

May 2, 2022

Fully-typed utilities for defining, validating and building your document head

zhead Typed utilities for defining, validating and building best-practice document head's. Status: Pre-release Please report any issues 🐛 Made poss

Dec 21, 2022

A TypeScript library for OPAQUE Asymmetric Password-Authenticated Key Exchange Protocol

A TypeScript library for OPAQUE Asymmetric Password-Authenticated Key Exchange Protocol

opaque-ts This is a Typescript library for the Asymmetric Password-Authenticated Key Exchange (OPAQUE) protocol. Use Available at: @cloudflare/opaque-

Dec 30, 2022

This package generates a unique ID/String for different browsers. Like chrome, Firefox and any other browsers which supports canvas and audio Fingerprinting.

This package generates a unique ID/String for different browsers. Like chrome, Firefox and any other browsers which supports canvas and audio Fingerprinting.

Broprint.js The world's easiest, smallest and powerful visitor identifier for browsers. This package generates a unique ID/String for different browse

Dec 25, 2022

A URL builder library for JavaScript, TypeScript

url-naong url-naong is url builder that is inspired by urlcat naong is korean name of Meowth(pokemon monster) install npm install url-naong --save Us

Jul 17, 2022

A simple easy to use vanilla JavaScript library for creating input fields that accept multiple email addresses

MeiMei - Multiple Email Input MeiMei: A simple easy to use vanilla JavaScript library for creating input fields that accept multiple email addresses.

Apr 13, 2022
Releases(v2.0.0)
Owner
J.Delauney
Développeur informatique web Entrepreneur freelance "L'Homme devrait mettre autant d'ardeur à simplifier sa vie qu'il met à la compliquer" - Henri Bergson
J.Delauney
Backend API Rest application for ShortLink, a URL shortening service where you enter a valid URL and get back an encoded URL

ShortLink - The Shortest URL (API) Sobre o Projeto | Como Usar | Importante! Sobre o projeto The Shortest URL é um projeto back-end de ShortLink, um s

Bruno Weber 2 Mar 22, 2022
Grupprojekt för kurserna 'Javascript med Ramverk' och 'Agil Utveckling'

JavaScript-med-Ramverk-Laboration-3 Grupprojektet för kurserna Javascript med Ramverk och Agil Utveckling. Utvecklingsguide För information om hur utv

Svante Jonsson IT-Högskolan 3 May 18, 2022
An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

An npm package for demonstration purposes using TypeScript to build for both the ECMAScript Module format (i.e. ESM or ES Module) and CommonJS Module format. It can be used in Node.js and browser applications.

Snyk Labs 57 Dec 28, 2022
Email Genie Allows autocomplete on email field by providing a list of domain suggestions (gmail.com, outlook.com, etc.).

Allows users to easily and quickly complete an email field by providing a list of domain suggestions (gmail.com, outlook.com, etc.). This package stands out for its flexibility, its compatibility with libraries / frameworks, but especially its use of basic HTML and Javascript functionalities that maximize the native behavior of desktop AND mobile browsers.

Simon Arnold 3 Oct 4, 2022
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
A tiny (108 bytes), secure, URL-friendly, unique string ID generator for JavaScript

Nano ID English | Русский | 简体中文 | Bahasa Indonesia A tiny, secure, URL-friendly, unique string ID generator for JavaScript. “An amazing level of sens

Andrey Sitnik 19.6k Jan 8, 2023
A little toy password manager made for a university class

Eddy Passbear's Password Manager A little toy password manager made for a university class. Powered by Remix, Prisma and the air we breathe. Step-by-s

Kacper Seredyn 2 Jan 30, 2022
Dynamically resize, format and optimize images based on url modifiers.

Local Image Sharp Dynamically resize, format and optimize images based on url modifiers. Table of Contents ✨ Features ?? Installation ?? Usage Contrib

Strapi Community 30 Nov 29, 2022
A jQuery-free general purpose library for building credit card forms, validating inputs and formatting numbers.

A jQuery-free general purpose library for building credit card forms, validating inputs and formatting numbers.

Jesse Pollak 528 Dec 30, 2022