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

property-validation

v1.0.5

Published

Makes validation easy for frontend or backend apps

Downloads

2

Readme

property-validation

Chainable validation of object properties for any JS application such as Angular, React and Node applications. Designed to be used as ES6 class. Works with redux-form out of the box.

Features

  • Chainable, e.g.

    const validate = new Validation()
      .require('firstName') // using default error message
      .require('lastName', 'last name is required') // using custom error message
      .validEmail('email')
      .getErrors();
  • Supports nested path, e.g.

    const validate = new Validation()
      .require('address.street.name')
      .getErrors();
  • Supports array in path, e.g.

    const validate = new Validation()
      .require('other.hobbies.type') // hobbies is an array
      .getErrors();
  • Works with redux-form out of the box, example here

  • Can be extended with custom validations

    class MyValidation extends Validation {
      validateMyField(field, message) {
        return this.validation(field, message || 'customized default message', value => myValiateFunc(value));
      }
    }
    
    const validate = new MyValidation()
      .require('firstName')
      .validateMyField('fieldName', 'customized message')
      .getErrors();

Installation

npm install property-validation --save

Test

npm test

Usage

Simple use

import { Validation } from 'property-validation';
import { expect } from 'chai';

const values = {
  firstName: 'JohnLongFirstName',
  lastName: 'Smith'
};

const errors = new Validation(values)
  .require('email', 'email is missing')
  .maxLength('firstName', 'firstName is too long', 15)
  .getErrors();

expect(errors).to.deep.equal({
  email: 'email is missing',
  firstName: 'firstName is too long'
}); // true

Use with redux-form

import React, { Component, PropTypes } from 'react'
import { Field, FieldArray, reduxForm } from 'redux-form'

class Example extends Component {
  constructor() {
    super();
    this.renderHobbies = this.renderHobbies.bind(this);
  }
  renderHobbies({ fields }) {
      return (
          <div>
            { fields.map((hobby, index) => (
                <div key={index}>
                    <Field
                        name={`${hobby}.type`}
                        component={Input}
                    >
                    <Field
                        name={`${hobby}.name`}
                        component={Input}
                    >
                </div>
            )) }
          </div>
      );
  }
  render() {
    return (
      <form onSubmit={this.props.handleSubmit(this.nextStep)}>
        <Field
          name="firstName"
          component="Input"
        />
        <FieldArray name="hobbies" component={this.renderHobbies}/>
      </form>
    );
  }
}

const validate = new Validation(values)
    .require('firstName')
    .require('hobbies.type')
    .getErrors();

export default reduxForm({
    form: 'ExampleForm',
    validate
})

Existing validations

  • validEmail(fieldName, message) fieldName: required. The key of the property. message: optional. Default message is 'invalid email'.

    new Validation(values).validEmail('email', 'Email is invalid').getErrors()
  • validInteger(fieldName, message) fieldName: required. The key of the property. message: optional. Default message is 'invalid integer'.

    new Validation(values).validInteger('age', 'Number is not integer').getErrors()
  • maxLength(fieldName, maxLength, message) fieldName: required. The key of the property. maxLength: required. Maximum length of the string. message: optional. Default message is 'max length exceeded'.

    new Validation(values).maxLength('password', 20, 'Password is too long').getErrors()
  • containsOnly(fieldList, message) fieldList: required. An array of valid keys of the property. message: optional. Default message is `body should only contain ${fieldList.join(', ')}`.

    new Validation(values).containsOnly(['username', 'password'], 'body should only contain username, password').getErrors()
  • require(fieldName, message) fieldName: required. The key of the property, or '/' which means the property itself. message: optional. Default message is 'property is required but missing' or 'body is required but missing'.

    new Validation(values).require('email', 'require email').getErrors()
    new Validation(values).require('/', 'body cannot be empty').getErrors()

Pull Requests are welcomed to add more validations!

Notes

  • For nested properties with arrays, validation message for first element will be undefined if validation passed for the first element but failed for one of the rest. e.g.

      const values = {
        persons: [
          {
            firstName: 'John',
            lastName: 'Smith',
            hobbies: [
              {
                type: 'sport',
                name: 'soccer'
              },
              {
                type: 'sport',
                name: 'basketball'
              }
            ]
          },
          {
            firstName: 'Alex',
            lastName: 'Turner',
            hobbies: [
              {
                name: 'soccer'
              },
              {
                type: 'sport',
                name: 'basketball'
              }
            ]
          }
        ]
      };
      const errors = new Validation(values)
        .require('persons.hobbies.type', 'missing')
        .getErrors();
    
      expect(errors).to.deep.equal({
        persons: [
          undefined,
          {
            hobbies: [
              { type: 'missing' }
            ]
          }
        ]
      }); // true
  • Validations, except for require, do not validate null or undefined values. For example, if values.firstName is undefined, new Validation(values).validInteger('firstName') does not give validation error. In order to validate null or undefined values, 'require' should be added before other validations in the chain. E.g. new Validation(values).require('firstName').validInteger('firstName').

  • In order to extend Validation with custom validations, this.validation() should be used if it is to validate against a specified path, e.g.

    class MyValidation extends Validation {
      minLength(field, message, minlength) {
        return this.validation(field, message || 'below minimum length', value => (value >= minlength));
      }
    }

    If it is to validate against the whole object then this.validation should not be used. e.g.

    class MyValidation extends Validation {
      bodyIsArray(message) {
        if (!Array.isArray(this.values)) {
          this.errors.body = message || 'body should be an array';
        }
        return this;
      }
    }

Pull Requests welcomed!!