Git Product home page Git Product logo

ember-validation's Introduction

@zestia/ember-validation

This lightweight addon lets you validate an object, or an array of objects. It will return a structured response with an array of error messages for anything that failed a constraint. Or, null if it passes validation.

Installation

ember install @zestia/ember-validation

Demo

https://zestia.github.io/ember-validation/

Features

Example

import validate from '@zestia/ember-validation';
import {
  present,
  maxLength,
  truthy,
  email,
  date
} from '@zestia/ember-validation/constraints';

const person = {
  id: 1,
  name: '',
  emailAddress: 'joe@bloggs',
  dateOfBirth: null,
  terms: false
};

const constraints = {
  name() {
    return [
      present({ message: 'Please enter your name' }),
      maxLength({ max: 255 })
    ];
  },

  emailAddress() {
    return [present(), email()];
  },

  dateOfBirth() {
    return [present(), date({ format: 'dd/MM/yyyy' })];
  },

  terms() {
    return [truthy({ message: 'Please accept the terms' })];
  }
};

const errors = await validate(person, constraints);

/**
 *  {
 *    name: [
 *      'Please enter your name'
 *    ],
 *    terms: [
 *      'Please accept the terms'
 *    ],
 *    emailAddress: [
 *      'Invalid email'
 *    ],
 *    dateOfBirth: [
 *      'Required value',
 *      'Invalid date, expecting dd/MM/yyyy'
 *    ]
 *  }
 */

Adhoc Constraints

You can validate properties that aren't actually on the object being validated. Here is a contrived example...

const person = {
  firstName: 'Joe',
  lastName: 'Bloggs'
};

const constraints = {
  firstName() {
    return [present()];
  },

  lastName() {
    return [present()];
  },

  name() {
    return [nameIsUnique];
  }
};

const errors = await validate(person, constraints);

/**
 *  {
 *    firstName: null,
 *    lastName: null,
 *    name: ['Must be unique']
 *  }
 */

const names = ['Joe Bloggs'];

function nameIsUnique(value, object) {
  if (names.includes(`${object.firstName} ${object.lastName}`)) {
    return;
  }

  return 'Must be unique';
}

Dynamic Constraints

Because constraints are functions, this allows for a very powerful approach for validating arrays of objects. For example, imagine you have an array of items of a varying types.

const items = [
  { id: 1, value: '', type: 'text' },
  { id: 2, value: '', type: 'number' },
  { id: 3, value: '', type: 'email' },
  { id: 4, value: '', type: 'date' }
];

const constraints = (item) => {
  return {
    value() {
      switch (item.type) {
        case 'text':
          return [present()];
        case 'number':
          return [present(), number()];
        case: 'email':
          return [present(), email()];
        case: 'date':
          return [present(), date({ format: 'dd/MM/yyyy' })];
        default:
          return [];
      }
    }
  };
}

const errors = await validate(items, constraints);

/*
 *  [
 *    {
 *      value: ['Required value']
 *    },
 *    {
 *      value: ['Required value', 'Invalid number']
 *    },
 *    {
 *      value: ['Required value', 'Invalid email']
 *    },
 *    {
 *      value: ['Required value', 'Invalid date, expecting dd/MM/yyyy']
 *    }
 *  ]
 */

Constraints

  • bigDecimal
    • optional
    • message
    • maxIntegerDigits
    • maxDecimalDigits
  • date
    • optional
    • format
    • mesaage
  • email
    • optional
    • message
  • greaterThan
    • optional
    • value
    • mesaage
  • lessThan
    • optional
    • value
    • mesaage
  • maxLength
    • max
    • message
  • minLength
    • min
    • message
  • number
    • optional
    • message
  • phoneNumber
    • optional
    • message
  • present
    • message
  • truthy
    • message

Utils

  • flattenErrors
    Flattens a validation result into a single array of all the messages.

  • collateErrors
    Flattens a validation result into an array of the messages for each field.

ember-validation's People

Contributors

amk221 avatar ember-tomster avatar grayt0r avatar philliphaines avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.