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

onsubmit

v0.0.19

Published

Simple validation utilities in typescript.

Downloads

61

Readme

onSubmit

Description

onsubmit is the simplest, least set-up needing way to validate an input or a form. On the client or on the server.

Features

  • Light-weight. (~1KB gzipped)
  • Simple API.
  • Zero dependencies.

Install

  npm i onsubmit

Quickstart

import { validateField } from 'onsubmit';

const firstNameRules = {
  required: { criterion: true, message: 'First Name is required' },
  minLength: { criterion: 3, message: 'Minimum length is 3' },
  maxLength: { criterion: 10, message: 'Maximum length is 10' },
};

// recieve an array of errors
const errors = validateField('Ammar', 'firstName', firstNameRules);

API

Methods

| Function | Description | Parameters | Returns | |-----------------|-------------------------------------------------------|-------------------------------------------------------------------|--------------------| | validateField | Validates a single form field against specified rules.| value: The string value of the field. name: Name of the field. rules: Object containing validation rules. | Array of FieldError objects, each containing the name of the field and the error message. | | validateForm | Validates an entire form. | values: A key-value pair object of field names and values. rules: A key-value object which maps field names to their rules . | Array of FieldError objects for the entire form. |

Validation Rules

| Rule | Description | Expected Value | |------------|----------------------------------------------|--------------------| | minLength | Minimum length of the field's value. | Number (length) | | maxLength | Maximum length of the field's value. | Number (length) | | pattern | Regex pattern the field's value should match.| RegExp | | custom | Custom validation logic. | Function | | required | Whether the field is required. | Boolean |

Examples

Validate a single field

import { validateField } from 'onsubmit';

const emailRules = {
  required: { criterion: true, message: 'Email is required' },
  pattern: {
    criterion: /^[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/,
    mesaage: 'Invalid email',
  },
};

const errors = validateField('[email protected]' , 'email', emailRules);

Custom validation logic


import { validateForm } from 'onsubmit';

const rulesObject = {
  custom: {
    criterion: (value) => value === password,
    message: 'Passwords do not match',
  }
};

const errors = validateField(passwordRepeat, 'passwordRepeat', rulesObject);

Validate some data

import { validateForm } from 'onsubmit';

const rulesObject = {
  minLength: { criterion: 3, message: 'Minimum length is 3' },
  maxLength: { criterion: 10, message: 'Maximum length is 10' },
  pattern: { criterion: /^[a-z]+$/, message: 'Only lowercase letters allowed' },
  custom: { criterion: (value) => value !== 'example', message: 'Value cannot be "example"' },
  required: { criterion: true, message: 'Field is required' },
};

const data = {
  firstName: 'Ammar',
  lastName: 'Halees',
  email: '[email protected]',
};

const errors = validateForm(data, rulesObject);

Validate a form

import { validateForm } from 'onsubmit';

const handleOnsubmit = (e) => {
  e.preventDefault();

  const formData = new FormData(e.currentTarget);
  const data = Object.fromEntries(formData);
  const errors = validateForm(data, RulesMap);
};

Utils and patterns

utils

onsubmit provides a set of utility functions and patterns to help you build your forms.

| Function Name | Type Signature | Description | |-------------------|----------------------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------| | isDateObject | (value: unknown) => value is Date | Checks if the given value is a valid Date object. | | isString | (value: unknown) => value is string | Determines if the provided value is a string. This includes both string literals and String objects. | | isNumber | (value: unknown) => value is number | Verifies if the value is a number and is finite. | | isNullOrUndefined | (value: unknown) => value is null \| undefined | Checks if the value is either null or undefined. | | isObject | <T extends object>(value: unknown) => value is T | Determines if a value is an object. This excludes null, arrays, and Date objects. | | isFile | (element: HTMLInputElement) => element is HTMLInputElement | Checks if an HTML input element is of type file. |

_patterns

  1. email
  2. uri
  3. alphanumeric
  4. cuid
  5. kebabCase
  6. arabic

FAQ

Which rule object has precedence?

The required rule has the highest precedence. The remaining rules are evaluated in the order they are specified in the rulesObject.

Types


type Criterion = string | number | CustomFunction | boolean | RegExp;

interface Rule {
criterion: Criterion;
message: string;
}

type FormDataShape = KeyValuePair | { [k: string]: FormDataEntryValue };

interface RulesObject {
required?: Rule;
minLength?: Rule;
maxLength?: Rule;
pattern?: Rule;
custom?: Rule;
}

TODO

  • onlySecure opt-out rule.
  • minDate rule.
  • maxDate rule.
  • minTime rule.rule
  • maxTime rule
  • file rule: { minSize, maxSize, type, name }
  • cardNumber pattern.
  • cardCompany utility.
  • Benchmarking
  • Allow for multiple patterns