npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

js-formdata-validator

v0.2.2

Published

JS Form Validator is a simple form data validation library for JavaScript. It provides a set of base rules for checking the type and value of various inputs, and allows you to define custom rules as well.

Downloads

864

Readme

JS Form Validator

JS Form Validator is a simple form data validation library for JavaScript. It provides a set of base rules for checking the type and value of various inputs, and allows you to define custom rules as well.

Installation

To install JS Form Validator, use one of the following package managers:

npm install --save js-formdata-validator
pnpm add js-formdata-validator

Nuxt 2 Installation

// nuxt.config.js
// Add transpile
build: {
	transpile: [/js-formdata-validator/],
},

Usage

To use JS Form Validator, import the Validator class and create a new instance, passing in an object with the following properties:

  • formData: An object containing the form data to be validated.
  • rules: An object specifying the validation rules for each field in the form data. (rules is not required to be pass as an parameter here) Here's an example of how to use JS Form Validator to validate a form with a required name field:
import { Validator } from "js-formdata-validator";

const formData = {
    name: null,
    deep: {
        neested: {
            object: {
                value: null
            }
        }
    },
    arrayObject: [
        {
            objectName: "object a name"
        },
        {
            objectName: null
        },
        {
            objectName: "object c name"
        },
    ]
};
const validator = new Validator({
  formData: formData,
  rules: {
    name: ["required"],
    "deep.nested.object.value": ["required"],
    "arrayObject.*.objectName": ["required"]
  },
});

// Validate the form data
await validator.validate();

// Check if the validation failed
if (validator.fail()) {
  // Get the validation error messages
  const error = validator.getErrorBag();
  console.log(error); // Output: {name: ["The field is required."], "deep.nested.object.value": ["The field is required."], "arrayObject.1.objectName": ["The field is required."]}
}

Base Rules

JS Form Validator provides the following base rules for validating form data:

  • required: checks if the value is undefined, an empty string, or null.
  • array: checks if the value is an instance of the Array class.
  • integer: checks if the value is an integer using the Number.isInteger() method.
  • numeric: checks if the value is an instance of the Number class.
  • string: checks if the value is a string.
  • boolean: checks if the value is a boolean.
  • allowed: checks if the value is included in a list of allowed values passed as arguments to the function.
  • image: checks if the value is an instance of the File class, and also checks if the file's MIME type starts with "image/".
  • size: checks if the value is an instance of the File class, and also checks if the file's size is within a specified range.
  • email: checks if the value is an email value
  • min: checks if the value is more than min value

Extends Custom Rules

JS Form Validator provides extendable custom rule to be runs alongside base rules, heres the code example:

const formData = {
    age: 25,
};
const validator = new Validator({
    formData: formData,
    rules: {
        age: ["custom"],
    },
}).mergeCustomRules({
    custom(value) {
        if (value === 25) {
            return "Test Error";
        }
    },
});

// Validate the form data
await validator.validate();

// Check if the validation failed
if (validator.fail()) {
  // Get the validation error messages
  const error = validator.getErrorBag();
  console.log(error);
}

Function parameters

We can also parse parameters to the custom rules

const formData = {
  age: 25
};
const validator = new Validator({
  formData: formData,
  rules: {
    age: ["ageBetween:26,50"]
  },
})
validator.mergeCustomRules({
    ageBetween(value, paramA, paramB) {
        // paramA will be 26
        // paramB will be 50
        if (value < paramA || value > paramB) {
            return `Age must be between ${paramA} - ${paramB}`;
        }
    },
});

Anonymous Function

Or set anonymous function inside the array rules

const formData = {
  age: 25
};
const validator = new Validator({
  formData: formData,
  rules: {
    age: [
        (value) {
            const min = 26
            const max = 50
            if (value < min || value > max) {
                return `Age must be between ${min} - ${max}`;
            }
        }
    ]
  },
})

Async / Await syntax

It can also use async / await syntax to fetch data and wait it to be fetched from some external source

const formData = {
  age: 25
};
const validator = new Validator({
  formData: formData,
  rules: {
    age: [
        async (value) {
            const { min, max } await fetch('/path/to/your/api');
            if (value < min || value > max) {
                return `Age must be between ${min} - ${max}`;
            }
        }
    ]
  },
})