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

react-form-utils-dev

v0.0.10

Published

Utilidades avanzadas para manejo de formularios en React

Downloads

12

Readme

@form-utils-dev

Utilidades JavaScript y Hook Avanzado para Formularios en React

Índice

  1. Instalación
  2. Validación de Tipos
  3. Manipulación de Arrays
  4. Manipulación de Objetos
  5. Parseo y Formateo de Números
  6. Hook useAdvancedForm
  7. Licencia

Instalación y Configuración

  1. Instala el paquete usando npm:
npm install @form-utils-dev
  1. Configura el store de Redux y el Provider en tu aplicación:
// src/index.js o src/main.jsx
import React from 'react';
import ReactDOM from 'react-dom/client';
import { FormProvider, configureStore } from '@form-utils-dev';
import App from './App';

const store = configureStore();

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <FormProvider store={store}>
        <App/>
    </FormProvider>
  </React.StrictMode>
);

Validación de Tipos

Uso Simple

import { isString, isNumber, isObject, isArray, isBoolean } from '@form-utils-dev';

console.log(isString('Hola mundo')); // true
console.log(isNumber(42)); // true
console.log(isObject({ a: 1, b: 2 })); // true
console.log(isArray([1, 2, 3])); // true
console.log(isBoolean(false)); // true

Uso Avanzado

import { isString, isNumber, isObject, isArray, isValid } from '@form-utils-dev';

// Validación de string con opciones
console.log(isString(""));                   // true
console.log(isString(123));                  // false
console.log(isString(null));                 // false
console.log(isString(undefined));            // false

console.log(isString("123", true));          // true
console.log(isString("123.45", true));       // true
console.log(isString("123,45", true));       // true
console.log(isString("-123.45", true));      // true
console.log(isString("1e5", true));          // true
console.log(isString("", true));             // false
console.log(isString("123abc", true));       // false
console.log(isString("Infinity", true));     // false
console.log(isString("NaN", true));          // false

// Validación de número con rango
console.log(isNumber(Infinity, { allowInfinity: true }));  // true
console.log(isNumber(NaN, { allowNaN: true }));            // true
console.log(isNumber('42', { allowString: true }));        // true
console.log(isNumber(42, { min: 0, max: 100 }));           // true
console.log(isNumber(42, { min: 50 }));                    // false
console.log(isNumber(3.14, { integer: true }));            // false
console.log(isNumber(42, { integer: true }));    

// Validación de objeto con opciones
console.log(isObject({}));  // true
console.log(isObject([], { allowArrays: true }));  // true
console.log(isObject(() => {}, { allowFunctions: true }));  // true
console.log(isObject(null, { allowNull: true }));  // true
console.log(isObject({}, { notEmpty: true }));  // false
console.log(isObject({ a: 1 }, { notEmpty: true }));  // true
console.log(isObject({ a: 1, b: 2 }, { notEmpty: true, ignoreKeys: ['a', 'b'] }));  // false
console.log(isObject(Object.create({ a: 1 }), { notEmpty: true, considerPrototype: true }));  // true

// Validación de array con validador de elementos
console.log(isArray([]));                     // true
console.log(isArray([1, 2, 3]));              // true
console.log(isArray({}));                     // false
console.log(isArray('array'));       
console.log(isArray([], { allowEmpty: false }));  // false
console.log(isArray([1, 2, 3], { itemValidator: (item) => typeof item === 'number' }));  // true
console.log(isArray([1, '2', 3], { itemValidator: (item) => typeof item === 'number' }));  // false

// Validación personalizada
console.log(isValid(null));  // false
console.log(isValid(undefined));  // false
console.log(isValid(''));  // false
console.log(isValid('', { allowEmpty: true }));  // true
console.log(isValid([]));  // false
console.log(isValid([], { allowEmpty: true }));  // true
console.log(isValid(0));  // true
console.log(isValid(0, { allowZero: false }));  // false
console.log(isValid(NaN));  // false
console.log(isValid(NaN, { allowNaN: true }));  // true
console.log(isValid('abc', { validValues: ['abc', 'def'] }));  // true
console.log(isValid('ghi', { validValues: ['abc', 'def'] }));  // false
console.log(isValid(42));  // true
console.log(isValid({ key: 'value' }));  // true

Manipulación de Arrays

Uso Simple

import { removeItemFromArray, mergeUniqueElements } from '@form-utils-dev';

const array = [1, 2, 3, 4, 5];
console.log(removeItemFromArray(array, 3)); // [1, 2, 4, 5]

const array1 = [1, 2, 3];
const array2 = [3, 4, 5];
console.log(mergeUniqueElements(array1, array2)); // [1, 2, 3, 4, 5]

Uso Avanzado

import { removeItemFromArray, compareArrays, addIfNotExists } from '@form-utils-dev';

// Eliminar elementos con opciones avanzadas
const arr1 = [1, 2, 3, 2, 4, 2, 5];
const arr2 = [1, 2, 3, 2, 4, 2, 5];
console.log(removeItemFromArray(arr1, 2));  // [1, 3, 4, 5]
console.log(removeItemFromArray(arr1, 2, { all: false }));  // [1, 3, 2, 4, 2, 5]
console.log(removeItemFromArray(arr1, [2, 4]));  // [1, 3, 5]
console.log(removeItemFromArray(arr1, x => x % 2 === 0));  // [1, 3, 5];
console.log(removeItemFromArray(arr2, 2, { inPlace: true }));  // [1, 3, 4, 5]

// Comparar arrays con opciones personalizadas
console.log(compareArrays([1, 2, 3], [3, 4, 5])); // true (tienen elementos comunes)
console.log(compareArrays([1, 2, 3], [4, 5, 6])); // false (no tienen elementos comunes)

console.log(compareArrays([1, 2, 3], [1, 2, 3], { exactMatch: true })); // true (son idénticos)
console.log(compareArrays([1, 2, 3], [1, 2, 3, 4], { exactMatch: true })); // false (no son idénticos)

console.log(compareArrays([1, 2, 3], ['1', '2', '3'], { exactMatch: true, strict: false })); // true (idénticos con comparación no estricta)
console.log(compareArrays([1, 2, 3], ['1', '2', '3'], { exactMatch: true, strict: true })); // false (no idénticos con comparación estricta)

console.log(compareArrays([{id: 1}, {id: 2}], [{id: 2}, {id: 1}], {
  exactMatch: true,
  comparator: (a, b) => a.id === b.id
})); // true (idénticos basados en la comparación de 'id')

console.log(compareArrays([1, 2, 3], [3, 4, 5], { threshold: 2 })); // false (no tienen suficientes elementos comunes)

try {
  compareArrays("not an array", [1, 2, 3]);
} catch (error) {
  console.error(error.message); // "Ambos argumentos deben ser arrays."
}

Manipulación de Objetos

Uso Simple

import { cleanObject, excludeProperties } from '@form-utils-dev';

const obj = { a: 1, b: null, c: undefined, d: 2 };
console.log(cleanObject(obj)); // { a: 1, d: 2 }

const objWithProps = { a: 1, b: 2, c: 3, d: 4 };
console.log(excludeProperties(objWithProps, ['b', 'd'])); // { a: 1, c: 3 }

Uso Avanzado

import { cleanObject, excludeProperties } from '@form-utils-dev';

// Limpieza de objeto con opciones
const obj = { a: 1, b: null, c: undefined, d: '', e: 0 };
console.log(cleanObject(obj, { 
  replaceWithEmptyString: true, 
  removeEmpty: true 
})); // { a: 1, e: 0 }

// Exclusión de propiedades con opciones avanzadas
const nestedObj = { a: 1, b: { c: 2, d: 3 }, e: 4 };
console.log(excludeProperties(nestedObj, ['b.c', 'e'], { 
  deep: true, 
  ignoreCase: true 
})); // { a: 1, b: { d: 3 } }

Parseo y Formateo de Números

Uso Simple

import { parseFloat, removeDecimalIfZero } from '@form-utils-dev';

// Ejemplos de uso parseFloat
console.log(parseFloat('1,234.56')); // 1234.56
console.log(parseFloat('1.234,56', { decimalSeparator: ',', thousandsSeparator: '.' })); // 1234.56
console.log(parseFloat('  1000  ', { trimWhitespace: false })); // 1000
console.log(parseFloat('no es un número', { defaultValue: -1 })); // -1

console.log(removeDecimalIfZero(42.00)); // 42

Uso Avanzado

import { parseFloat, removeDecimalIfZero } from '@form-utils-dev';

// Parseo de float con opciones personalizadas
console.log(parseFloat('1.234,56', { 
  decimalSeparator: ',', 
  thousandsSeparator: '.' 
})); // 1234.56

// Remover decimales con precisión
console.log(removeDecimalIfZero(123.4567, { decimalPlaces: 2 })); // 123.46

Hook useAdvancedForm

Uso Simple

import React from 'react';
import { useAdvancedForm } from '@form-utils-dev';

const SimpleForm = () => {
  const { values, handleInputChange, handleSubmit } = useAdvancedForm({
    initialState: { name: '', email: '' }
  });

  const onSubmit = (formValues) => {
    console.log('Formulario enviado:', formValues);
  };

  return (
    <form onSubmit={(e) => handleSubmit(e, onSubmit)}>
      <input
        name="name"
        value={values.name}
        onChange={handleInputChange}
        placeholder="Nombre"
      />
      <input
        name="email"
        value={values.email}
        onChange={handleInputChange}
        placeholder="Email"
      />
      <button type="submit">Enviar</button>
    </form>
  );
};

Uso Avanzado

import React from 'react';
import { useAdvancedForm } from '@form-utils-dev';

const AdvancedForm = () => {
  const {
    values,
    errors,
    handleInputChange,
    handleSubmit,
    setFieldValue,
    resetFields,
    isFormValid,
    getFieldProps
  } = useAdvancedForm({
    initialState: {
      name: '',
      email: '',
      age: '',
      preferences: []
    },
    onValidate: {
      email: (value) => {
        if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(value)) {
          return 'Email inválido';
        }
      },
      age: (value) => {
        if (isNaN(value) || value < 18) {
          return 'Debe ser mayor de 18 años';
        }
      }
    },
    onFieldChange: (name, value) => {
      console.log(`Campo ${name} cambiado a: ${value}`);
    },
    customTransformers: {
      age: (value) => parseInt(value, 10)
    }
  });

  const handlePreferenceChange = (e) => {
    const { value, checked } = e.target;
    setFieldValue('preferences', 
      checked 
        ? [...values.preferences, value]
        : values.preferences.filter(pref => pref !== value)
    );
  };

  const onSubmit = (formValues) => {
    console.log('Formulario enviado:', formValues);
  };

  return (
    <form onSubmit={(e) => handleSubmit(e, onSubmit)}>
      <input {...getFieldProps('name')} placeholder="Nombre" />
      {errors.name && <p>{errors.name}</p>}

      <input {...getFieldProps('email')} placeholder="Email" />
      {errors.email && <p>{errors.email}</p>}

      <input {...getFieldProps('age')} placeholder="Edad" type="number" />
      {errors.age && <p>{errors.age}</p>}

      <div>
        <label>
          <input
            type="checkbox"
            value="sports"
            checked={values.preferences.includes('sports')}
            onChange={handlePreferenceChange}
          />
          Deportes
        </label>
        <label>
          <input
            type="checkbox"
            value="music"
            checked={values.preferences.includes('music')}
            onChange={handlePreferenceChange}
          />
          Música
        </label>
      </div>

      <button type="submit" disabled={!isFormValid()}>Enviar</button>
      <button type="button" onClick={() => resetFields(['name', 'email'])}>
        Resetear Nombre y Email
      </button>
    </form>
  );
};

Contribución

Las contribuciones son bienvenidas. Por favor, asegúrate de actualizar los tests según corresponda.

Reportar Problemas

Si encuentras algún problema o tienes alguna sugerencia, por favor crea un issue en el repositorio de GitHub.

Changelog

Para ver los cambios recientes, consulta el archivo CHANGELOG.md.

Licencia

Este proyecto está licenciado bajo la Licencia MIT - vea el archivo LICENSE para más detalles.

MIT License

Copyright (c) 2024 Damien M.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

Agradecimientos

  • Inspirado en diversas bibliotecas de manejo de formularios y utilidades de JavaScript.

Notas de la Versión

Versión 0.0.2

  • Lanzamiento inicial de @form-utils-dev
  • Incluye funciones de validación de tipos
  • Utilidades para manipulación de arrays y objetos
  • Hook useAdvancedForm para manejo de formularios
  • Funciones de parseo y formateo de números

Versión 0.0.3 (Próximamente)

  • Mejoras en el rendimiento del hook useAdvancedForm
  • Nuevas utilidades para manipulación de fechas
  • Soporte mejorado para validación asíncrona