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

@coderan/validator

v2.1.2

Published

The smart React element validator

Downloads

8

Readme

Coderan: Validator

The smart React element validator

example workflow name codecov

Introduction

The goal of this package, is to simplify the struggle of validating elements in React, with a simple system which allows users to add their own rules.
The system communicates directly with the elements in the DOM, and is therefore widely compatible with other libraries, like Bootstrap.

The concept

Validator consists of two main elements, an Area and a Provider. Areas are a sort of wrappers having elements that need validation as their children. An area scans the underlying components and elements and indexes validatable elements.

Providers on the other hand are wrappers around areas, and allow them to communicate between each other. This communication is needed in order to match with values in other areas. It can also be used to validate all areas at once, and preventing actions to happen while not all areas are valid.

How to use

First, start with adding rules to the validator in order to use them. There are some rules pre-made, but more specific rules you have to create yourself.

import { Validator } from '@coderan/validator';
import { min } from '@coderan/rules/min';

Validator.extend('min', min);

Area

Basic usage:

import { ValidatorArea } from '@coderan/validator';

<ValidatorArea rules="required">
    <input name="username" />
</ValidatorArea>

When the input is focused and blurred, the required rule is called.

Every area needs a name. This name is used to index areas in the provider, and make meaningful error messages. When using multiple inputs within an area, i.e. when validating a multi-input date of birth, name prop is required when defining the ValidatorArea component. Like so:

import { ValidatorArea } from '@coderan/validator';

<ValidatorArea rules="min" name="dob">
    <input name="day" />
    <input name="month" />
    <input name="year" />
</ValidatorArea>

Showing errors:

import { ValidatorArea } from '@coderan/validator';

<ValidatorArea rules="min" name="dob">
    {({ errors }) => (
        <>
            <input name="username" />
            { errors.length && <span>{errors[0]}</span> }
        </>
    )}
</ValidatorArea>

Provider

Basic usage:

import { ValidatorProvider, ValidatorArea } from '@coderan/validator';

<ValidatorProvider>
    {({ validate }) => (
        <>
            <ValidatorArea rules="min" name="dob">
                <input name="day" />
                <input name="month" />
                <input name="year" />
            </ValidatorArea>
            <ValidatorArea rules="min" name="dob">
                <input name="day" />
                <input name="month" />
                <input name="year" />
            </ValidatorArea>
            <button
                onClick={() => validate(() => alert('valid'))}>Check</button>
        </>
    )}
</ValidatorProvider>

It is possible to give the validator a rules prop as well, whose rules apply to all underlying areas:

import { ValidatorProvider, ValidatorArea } from '@coderan/validator';

<ValidatorProvider rules="required">
    <ValidatorArea rules="min:5">
        {/* on blur, both required and min rules are applied */}
        <input name="username" /> 
    </ValidatorArea>
</ValidatorProvider>

Adding rules

With access to validator

import { Validator } from '@coderan/validator'
Validator.extend('test_types', (validator: Validator) => ({
    passed(): boolean {
        return validator.refs(undefined, HTMLInputElement).length === 1
            && validator.refs('test1', HTMLTextAreaElement).length === 1
            && validator.refs('test1').length === 1
            && validator.refs('test1', HTMLProgressElement).length === 0;
    },
    message(): string {
        return 'test';
    }
}));

or without

import { getValue, isInputElement, isSelectElement } from '@/utils/dom';

export default {
    passed(elements: HTMLElement[]): boolean {
        return elements.every((element: HTMLElement) => {
            if (isInputElement(element) || isSelectElement(element)) {
                const value = getValue(element);

                return value && value.length;
            }

            return true;
        })
    },

    message(): string {
        return `{name} is required`;
    }
};

You can create your own rules, as long as it follows this interface:

import { Validator } from '@coderan/validator';

/**
 * Function to access validator using the rule
 */
declare type RuleFunction = (validator: Validator) => RuleObject;

/**
 * Object structure rules must implement
 */
declare type RuleObject = {
    /**
     * Returns whether the rule passed with the given element(s)
     */
    passed(elements: HTMLElement[], ...args: string[]): boolean;
    /**
     * Message shown when the rule doesn't pass
     */
    message(): string;
}

export type Rule = RuleObject | RuleFunction;

Perhaps you would like to use a different name for the message than the name-attribute. That's perfectly fine!

import { ValidatorArea } from '@coderan/validator';

<ValidatorArea rules="required" validationName="Surname">
    {({ errors }) => (
        <>
            <input name="username" />
            { errors.length && <span>{errors[0]}</span> }
        </>
    )}
</ValidatorArea>

and when no value is present in the input, a message like "Surname is required" will appear.

Happy Coding!