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 🙏

© 2025 – Pkg Stats / Ryan Hefner

vfes-validator

v1.0.0

Published

Validator for web forms

Readme

Validador de formularios

Validador genérico de formularios en javascript.

Instalación

Como empezar

Lo único que tendremos que tener en cuenta, dentro del formulario de HTML, es que los elementos donde mostremos los mensajes de error deben llevar el atributo data-form-message.

<form id="form1" action="/" method="POST">
    <fieldset>
        <legend>Legend</legend>
        <div>
            <label for="textFieldExample">Label: </label>
            <input id="textFieldExample" type="text" name="textFieldExample" placeholder="Escribe algo" />
            <p data-form-message></p>
        </div>
        <div>
            <label for="nifFieldExample">NIF: </label>
            <input id="nifFieldExample" type="text" name="nifFieldExample" placeholder="Ej: 99999999Z" />
            <p data-form-message></p>
        </div>
        <div>
            <input type="submit" value="Input submit" />
        </div>
    </fieldset>
</form>

Inicialización de la librería

    const form = document.getElementById('form1');

    const validator = new Validator(form, {
        rules: {
            textFieldExample: {
                required: true,
                minlength: 2,
                maxlength: 8
            },
            nifFieldExample: {
                nif: true
            }
        },
        messages: {
            textFieldExample: {
                required: "Debe rellenar este campo",
                minlength: "El texto debe tener mínimo 2 caracteres",
                maxlength: "El texto debe tener máximo 8 caracteres"
            },
            nifFieldExample: {
                nif: "Debe escribir un NIF válido. Pj: 99999999Z"
            }
        }
    });

    validator.init();

Rules

Las reglas se pasan en un object y se debe asociar el name del input con el nombre de las reglas existentes. El formato es el siguiente:

    rules: {
        inputName: {
            ruleName: value
        }
    }

Las reglas disponibles por defecto son las siguientes:

|Rule Name |Value Type |Description | |----------------|-------------------------------|-------------------------| |cif |boolean | Formato de CIF | |cp |boolean | Formato de código postal| |digits |boolean | Solo dígitos | |email |boolean | Formato email | |maxlength |number | Tamaño máximo | |minlength |number | Tamaño mínimo | |nie |boolean | Formato de NIE | |nif |boolean | Formato de NIF | |required |boolean | Campo obligatorio |


Mensajes de error

Para añadir mensajes tenemos que incluir el objecto messages dentro de las opciones del validador. Su formato es el siguiente:

    messages: {
        inputName: {
            ruleName: 'Mensaje de error'
        }
    }

Otras opciones

Podemos añadir varias opciones más al validador de las antes mencionadas. Una de ellas es el object customRules. Con este objeto podemos definir nuestras propias reglas.

Los parámetros que nos devuelve el validador para ejecutar nuestra customRule son el input y el valor de la regla. El formato es el siguiente:

    //optional object
    customRules: {
        customRuleName: (input, ruleValue) => {
            return input.value === ruleValue;
        }
    },
    rules: {
        inputName: {
            customRuleName: "customValue"
        }
    },
    messages: {
        inputName: {
            customRuleName: "Los valores no coinciden"
        }
    }

Otra opción que tenemos es onfocusout lo que nos permite validar cada input al perder el foco. Simplemente añadiremos lo siguiente a las opciones:

{
    //optional object
    onfocusout: true
}

Por último, si queremos añadir una clase de error cuando la validación sea incorrecta añadiremos errorClass a las opciones del validador. Un ejemplo de ello:

{
    //optional object
    errorClass: "errorClass"
}