form-react-hooks

1.0.3 • Public • Published

useForm

Make form easily with react hooks

The most simple react form hook.

Installation

npm i --save form-react-hooks

Usage

Form

check basic example

import useForm from 'form-react-hooks';
import { validate } from './validate';
 
function Form() {
 
  let callback = () => {
    // submit values
  }
 
  let {
    handleChange,
    handleSubmit,
    values,
    errors,
  } = useForm(callback, validate)
 
  return (
    <React.Fragment>
      <form className="container" onSubmit={handleSubmit}>
        <div className="form-group">
          <label>Email address</label>
          <input 
            type="text"
            name="email"
            className="form-control"  
            placeholder="Enter email" 
            onChange={handleChange} 
            />
            {errors['email'] && <small className="form-text text-danger">{errors['email']}</small>}
        </div>
        <div className="form-group">
          <label>Password</label>
          <input 
          type="password" 
          name="password" 
          className="form-control" 
          placeholder="Password" 
          onChange={handleChange} 
          />
          {errors['password'] && <small className="form-text text-danger">{errors['password']}</small>}
        </div>
        <input 
            className="btn btn-primary" 
            type="submit" 
            value="Submit" 
            />
      </form>
    </React.Fragment>
  );
}
 
export default Form;
 

Validate

 
export const validate = values => {
    let errors = {};
    if (!values.email) {
        errors.email = 'Required';
    } else if (
        !/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}$/i.test(values.email)
    ) {
        errors.email = 'Invalid email address';
    }
    if (!values.password) {
        errors.password = "required"
    } else if (values.password.length < 5) {
        errors.password = "password must be at least 5 characters"
    }
 
    return errors;
}

License

MIT

Versions

Current Tags

  • Version
    Downloads (Last 7 Days)
    • Tag
  • 1.0.3
    0
    • latest

Version History

  • Version
    Downloads (Last 7 Days)
    • Published
  • 1.0.3
    0
  • 1.0.2
    1
  • 1.0.1
    1

Package Sidebar

Install

npm i form-react-hooks

Weekly Downloads

2

Version

1.0.3

License

ISC

Unpacked Size

44.4 kB

Total Files

8

Last publish

Collaborators

  • jaouadballat