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

predatorjs

v0.0.4

Published

Painless React Form Validator, Predator is basic form validator inspired by Laravel Validation

Downloads

2

Readme

Painless React Form Validator

Predator is a React Higher Order Component to validate form with basic validator. Predator is inspired by Laravel Validation

Install

Predator is available at npm

$ npm install --save predatorjs or $ yarn add predatorjs

Examples

This example is using Material-UI But don't worry Predator works with any form

import React, { Component } from 'react'
import TextField from 'material-ui/TextField'
import RaisedButton from 'material-ui/RaisedButton'
import withValidator from 'predatorjs'

class ExampleForm extends Component {
  constructor(props) {
    super(props)
    this.state = { ... }
  }

  handleChange = (key, value) => {
    this.setState({ form: { ...this.state.form, [key]: value } }, () =>
      this.props.validate(key, value) // Validate in setState callback
    )
  };

  handleSubmit = e => { ... };

  render() {
    const {
      validate,
      getErrorMessage,
      formIsValid
    } = this.props

    const { form } = this.state

    return (
      <form onSubmit={e => this.handleSubmit(e)}>
        <div style={{ maxWidth: 450, margin: '0 auto' }}>
          <h3 style={{ fontFamily: 'Helvetica' }}>Predator Example</h3>
          <div>
            <TextField
              hintText="Username"
              floatingLabelText="Username"
              fullWidth={true}
              value={form.username}
              onChange={({ target }) => this.handleChange('username', target.value)}
              errorText={getErrorMessage('username')}
            />
          </div>
          <div>
            <TextField
              name="fullname"
              hintText="Full Name"
              floatingLabelText="Full Name"
              fullWidth={true}
              value={form.fullname}
              onChange={({ target }) => this.handleChange('fullname', target.value)}
              errorText={getErrorMessage('fullname')}
            />
          </div>

          ... // other form components

          <div>
            <RaisedButton
              type="submit"
              label="Save"
              primary={true}
              disabled={!formIsValid}
            />
          </div>
        </div>
      </form>
    )
  }
}

/*
 * formRules is required
*/
const formRules = {
  username: 'required|alphanumeric|min:6|max:12',
  fullname: 'required',
  email: 'required|email',
  phone: 'num'
}

/*
 *  Form messages is optional
 *  Automaticaly use default messages
 *  if formMessages is not provided
*/
const formMessages = {
  required: 'Telolet! {form} can not be empty!',
  email: 'This {form} is not a valid email!',
  num: '{form} only accept number.'
}

export default withValidator(formRules, formMessages)(ExampleForm)

API

Props

validate(key, value)

Validating a form based on key. Key must be unique and also must be exist in formRules

onInitValidate('#formID')

Validating form on initialize. This method aims to validate form defaultValue. You may not need to use this method, this method usually used on form which has default value (Eg: Edit form).

If you need to use this method, you have to put this method in componentDidMount lifecycle. And don't forget to add selector to your form.

componentDidMount() {
  this.props.onInitValidate('#yourEditForm')
}

render() {
  return (
    <form id="yourEditForm">
      ...
    </form>
  )
}

formIsValid

Return true if all required form has been filled and no errors found.

getErrorMessage(key)

Return String. Get error message based on form key.

getErrorMessages()

Return Array Return array of error messages contains form name and their error message. Message format :

[
  {
    name: '',
    message: ''
  }
]

HOC

withValidator(formRules, [, formMessage])

Higher order component that return all props which have been mentioned above. First parameter is form rules. Form rules must be an object. For instances:

const formRules = {
  username: 'required|alphanumeric|min:6|max:12',
  fullname: 'required',
  email: 'required|email',
  phone: 'num'
}

Second parameter is optional, Predator will use default messages if this parameter is not provided. Error message example:

const formMessages = {
  required: 'Telolet! {form} can not be empty!',
  email: 'This {form} is not a valid email!',
  num: '{form} only accept number.',
  min: '{form} min length is {value} characters.',
  max: '{form} max length is {value} characters.'
}

Available Rules

These are available rules for a while. Feel free to add another rule by submitting PR

| Rules | Description | | ---------------|:------------------------------:| | required | Form can not be empty | | email | Validating Email | | url | Validating URL | | bool | Validating Bool | | ip | Validating IP | | date | Validating Date | | alpha | Only accept alphabet | | num | Only accept number | | alphanumeric | Only accept alphabet & number | | min | Minimal character | | max | Maximal character |

Todo

  1. Add another advance rules
  2. Add test case

License

MIT