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

flexible-form-validation

v1.0.11

Published

A flexible and reusable form validation package

Downloads

8

Readme

flexible-form-validation

A flexible and powerful form validation library for React applications.

Features

  • Easy-to-use validation schema creation
  • Support for various field types (string, email, number, date, etc.)
  • Customizable validation rules and error messages
  • Real-time field validation
  • Full form validation
  • Lightweight and performant

Installation

npm install flexible-form-validation

or if you're using yarn:

yarn add flexible-form-validation

Usage

Importing

import createValidationSchema, { validateField, validateForm } from 'flexible-form-validation';

Creating a Validation Schema

const validationSchema = createValidationSchema([
  { 
    name: 'username', 
    type: 'string', 
    required: true, 
    min: 3, 
    max: 20,
    messages: {
      'string.empty': 'Username is not allowed to be empty',
      'string.min': 'Username must be at least 3 characters long',
      'string.max': 'Username cannot exceed 20 characters'
    }
  },
  { 
    name: 'email', 
    type: 'email', 
    required: true 
  },
  { 
    name: 'age', 
    type: 'number', 
    min: 18, 
    max: 100,
    messages: {
      'number.min': 'You must be at least 18 years old',
      'number.max': 'Age cannot exceed 100'
    }
  },
  { 
    name: 'birthdate', 
    type: 'date', 
    required: true 
  }
]);

Validating a Single Field

const handleChange = useCallback((event) => {
  const { name, value } = event.target;
  setFormData(prev => ({ ...prev, [name]: value }));
  const fieldError = validateField(validationSchema, name, value);
  setTimeout(() => {setErrors(prev => ({ ...prev, [name]: fieldError[name] }));}, 2000);
}, [validationSchema]);

Validating the Entire Form

const handleSubmit = (e) => {
  e.preventDefault();
 const { isValid, errors } = validateForm(validationSchema, data);
    if (!isValid) {
         setErrors(errors);
         return;
       }
  // Proceed with form submission...
};

API Reference

createValidationSchema(fields)

Creates a validation schema based on the provided field configurations.

  • fields: An array of field objects, each containing:
    • name: Field name (string)
    • type: Field type ('string', 'email', 'number', 'date', etc.)
    • required: Whether the field is required (boolean)
    • min: Minimum value/length (number)
    • max: Maximum value/length (number)
    • messages: Custom error messages (object)

Returns a validation schema object.

validateField(schema, name, value)

Validates a single field.

  • schema: The validation schema created by createValidationSchema
  • name: The name of the field to validate
  • value: The value to validate

Returns an object with the field name as key and the error message (if any) as value.

validateForm(schema, data)

Validates the entire form.

  • schema: The validation schema created by createValidationSchema
  • data: An object containing all form data

Returns an object with isValid (boolean) and errors (object with field names as keys and error messages as values).

Example

Here's a complete example of how to use the library in a React component:

import React, { useState ,useCallback} from 'react';
import createValidationSchema, { validateField, validateForm } from 'flexible-form-validation';


function FormComponent() {
  const [formData, setFormData] = useState({ username: '', email: '', age: '' });
  const [errors, setErrors] = useState({});

  const validationSchema = createValidationSchema([
  { name: 'username', type: 'string', required: true, min: 3, max: 20 },
  { name: 'email', type: 'email', required: true },
  { name: 'age', type: 'number', min: 18, max: 100 }
]);

  const handleChange = useCallback((event) => {
    const { name, value } = event.target;
    setFormData(prev => ({ ...prev, [name]: value }));
    const fieldError = validateField(validationSchema, name, value);
     setTimeout(() => {setErrors(prev => ({ ...prev, [name]: fieldError[name] }));}, 2000);
  }, [validationSchema]);

  const handleSubmit = (e) => {
    e.preventDefault();
    const { isValid, errors } = validateForm(validationSchema, formData);
    if (!isValid) {
      setErrors(errors);
      return;
    }
    // Proceed with form submission...
    console.log('Form is valid!', formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        name="username"
        value={formData.username}
        onChange={handleChange}
        placeholder="Username"
      />
      {errors.username && <p>{errors.username}</p>}
      
      <input
        name="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Email"
      />
      {errors.email && <p>{errors.email}</p>}
      
      <input
        name="age"
        value={formData.age}
        onChange={handleChange}
        placeholder="Age"
        type="number"
      />
      {errors.age && <p>{errors.age}</p>}
      
      <button type="submit">Submit</button>
    </form>
  );
}

export default FormComponent;

License

MIT

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.