Skip to content

Fabricevladimir/simple-validator

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

JS Validation

A minimal JavaScript string validation library.

Table of Contents

Getting started

Installation using npm:

$ npm i --save @fabricefrancois/simple-validator

Usage

String validation is carried out in two steps:

  1. Create a schema.
  2. Validate the string.

Creating a Schema

To validate a property or a group of related properties, a blueprint (schema) containing the string validation rules to be tested against has to be configured. A new schema can be created or the pre-built PasswordSchema may be used if the value being validated is a password. A new schema is configured as follows:

// CommonJs
const Schema = require("@fabricefrancois/simple-validator").Schema;

// Using ES6
import { Schema, PasswordSchema } from "@fabricefrancois/simple-validator";

// Schema for a single property
const usernameSchema = new Schema()
  .min(6)
  .hasDigit()
  .hasUppercase("My custom error message")
  .label("Username");

// Schema for multiple properties. Note the use of the custom schema 'PasswordSchema'
const formSchema = {
  username: new Schema().min(6),
  password: new PasswordSchema()
};

Validating the Property

A string is validated using the rules set on its corresponding schema.

const usernameSchema = new Schema().min(6);
const result = usernameSchema.validate("abc123");

Related properties and strings can either be validated individually or be grouped together as a form and validated at once.

import { Schema, PasswordSchema, validateForm } from "@fabricefrancois/simple-validator";

const formSchema = {
  username: new Schema().min(6),
  password: new PasswordSchema()
};

// Individual validation
const result = formSchema.username.validate("abc123");

// Form validation
const form = {
  username: "abc123",
  password: "password"
}

const result = validateForm(form, formSchema)

When validating a form or single string, additional configurations can also be passed in to the validation function in the form of an options object.

const options = { includeLabel: true };

// Single value
const result = new Schema().min(6).validate("abc123", options);

// Form validation
const result = validateForm(form, formSchema, options)

The Result

When validating a single property, the validation function returns a PropertyValidationResult object with the result of the validation rules set in the schema.

const usernameSchema = new Schema.min(6).hasDigit("Custom error");

// Invalid string
let result = usernameSchema.validate("abc");

/*
result: {
  isValid: false,
  errors: [
    "must be at least 6 character(s) long",
    "Custom error"
  ]
}
*/

// Valid string
result = usernameSchema.validate("abc123");

// result: { isValid: true, errors: [] }

On the other hand, a FormValidationResult object is returned when validating a form. It contains the validation results of all the individual properties.

const formSchema = {
  username: new Schema().min(6),
  password: new Schema().hasUppercase()
};

// Invalid form
let form = {
  username: "abc1",
  password: "Password"
}

const result = validateForm(form, formSchema);

/*
result: {
  isValid: false,
  errors: {
    username: ["must be at least 6 character(s) long"]
  }
}
*/

// Valid form
let form = {
  username: "abc123",
  password: "Password"
}

const result = validateForm(form, formSchema);

// result: { isValid: true, errors: {} }

API Documentation

Schema

Creates a new Schema with set validation rules.

Public Methods:

constructor(customValidator) ⇒ this

Create new Schema.

Param Type Description
customValidator CustomValidator | CustomValidator[] The custom validator

max(length, message) ⇒ this

Set the maximum number of characters.

Param Type Description
length number The maximum number of characters
[message] string Custom error message

min(length, message) ⇒ this

Set the minimum number of characters.

Param Type Description
length number The maximum number of characters
[message] string Custom error message

label(value) ⇒ this

Add a label to pre-append to error messages.

Param Type Description
value number The label to pre-append to error messages

hasDigit(message) ⇒ this

Set property to contain at least one digit character.

Param Type Description
[message] string Custom error message

hasSymbol(message) ⇒ this

Set property to contain at least one special character.

Param Type Description
[message] string Custom error message

hasLowercase(message) ⇒ this

Set property to contain at least one lowercase character.

Param Type Description
[message] string Custom error message

hasUppercase(message) ⇒ this

Set property to contain at least one uppercase character.

Param Type Description
[message] string Custom error message

isRequired(message) ⇒ this

Set property to be required.

Param Type Description
[message] string Custom error message

hasPattern(regExpPattern, message) ⇒ this

Set a pattern to match.

Param Type Description
regExpPattern string | RegExp The pattern to match
[message] string Custom error message

hasMatchingProperty(name, message) ⇒ this

Set property a form property to match.

Param Type Description
name string The property to match
[message] string Custom error message

Example:

const form = { password: "Abc", confirmPassword: "def" };
const formSchema = {
  password: new Schema().hasUppercase(),
  confirmPassword: new Schema().hasMatchingProperty("password")
};

getMatchingProperty() ⇒ string

Return the name of the property to match.


addValidator(customValidator) ⇒ this

Add custom validator(s).

Param Type Description
customValidator CustomValidator | CustomValidator[] The custom validator

validate(value, options) ⇒ PropertyValidationResult

Validate a given string.

Param Type Description
value string The value to be validated
[options] ValidationOptions The validation configurations

PasswordSchema

Create a Schema custom made for passwords.

Public Properties:

strength

The level of password security. The higher the value (1-3), the more secure the password, the more requirements are added to the password schema.

Type: number


Public Methods:

constructor(strength) ⇒ PasswordSchema

Create a Password Schema.

Param Type Description
[strength] 1 | 2 | 3 The password security

validate(password, options) ⇒ PropertyValidationResult

Validate a given password.

Param Type Description
value string The password to be validated
[options] ValidationOptions The validation configurations

Note: A label of Password is automatically included in the schema.


ValidateForm

validateForm(form, formSchema, options) ⇒ FormValidationResult

Validate a form.

Type: Function

Name Type Description
form object The form to be validated
formSchema object The schemas for the entire form
[options] ValidationOptions The validation configurations

Example:

const form = { password: 'abcd', username: 'def' };
const options = { includeLabel: true }
const formSchema = {
  password: new PasswordSchema(1),
  username: new Schema().hasDigit().label('Username');
};

const result = validateForm(form, formSchema, options);
/*
result: {
  isValid: false,
  errors: {
    username: ['Username must include at least one digit']
  }
}
*/

Validators

Validator functions exported by the library:

Name Description
isEmail Check if input is a valid email address
hasDigit Check if input includes a digit
hasSymbol Check if input includes a special character
hasMaximum Check if input is of the specified maximum length
hasMinimum Check if input is of the specified minimum length
hasPattern Check if input matches given regex pattern
hasLowercase Check if input includes an lowercase character
hasUppercase Check if input includes an uppercase character

Example:

import { Validators } from "@fabrice/simple-validator";
// or
import isEmail from "@fabrice/simple-validator/lib";

const result = Validators.isEmail('abc@de'); // result: false

Type Definitions

CustomValidator

Type: Object

Properties:

Name Type Description
[input] * Value with which the validator function is called
[message] string Custom error message
validator ValidatorCallback Validator function to be called

ValidationOptions

Type: Object

Properties:

Name Type Description
[abortEarly] boolean Value with which the validator function is called
[includeLabel] boolean Custom error message
[includeRules] boolean Validator function to be called

FormValidationResult

Type: Object

Properties:

Name Type Description
[rules] object The validation rules (present when includeRules is set to true)
errors object The errors present in the form
isValid boolean Property detailing whether the form was validated successfully

Example:

{
  rules: { password: { minLength: false } },
  errors: { password: { ["Must include a lowercase character"] },
  isValid: false
}

PropertyValidationResult

Type: Object

Properties:

Name Type Description
[rules] object The validation rules (present when includeRules is set to true)
errors array The errors present in the property
isValid boolean Property detailing whether the value was validated successfully

Example:

{
  rules: { minLength: false },
  errors: ["Must include a lowercase character"],
  isValid: false
}

ValidatorCallback

validator(input, value, message) ⇒ true | false | message

Type: Function

Param Type Description
[input] * Custom input to setup validator function
value string The value to validate
[message] string Custom error message

Returns:

  • true when value is successfully validate
  • false when validation is unsuccessful
  • message when validation is unsuccessful and a custom error message was provided

Example:

function minimumValidator(input, value, message) {
  const pattern = new RegExp("^.{0," + length + "}$");
  return pattern.test(value) || errorMessage || false;
}

Contributing

Feel free to submit issues and requests!

  1. Fork the project repository on Github
  2. Clone the repository to your local machine
  3. Commit changes to a new branch
  4. Push your changes to your Github fork
  5. Submit a pull request so your changes can be reviewed

Acknowledgements

Special thanks to Will Lambert and Sabien Jarmin for their help and support. This project is also supported by oneleif, an open source development team trying to develop great software.

About

JavaScript string validator

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published