All Projects → 25th-floor → Spected

25th-floor / Spected

Licence: mit
Validation library

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to Spected

Valid.js
📝 A library for data validation.
Stars: ✭ 604 (-15.76%)
Mutual labels:  validation
Class Validator
Decorator-based property validation for classes.
Stars: ✭ 6,941 (+868.06%)
Mutual labels:  validation
Encoding
Go package containing implementations of efficient encoding, decoding, and validation APIs.
Stars: ✭ 705 (-1.67%)
Mutual labels:  validation
Vue Form
Form validation for Vue.js 2.2+
Stars: ✭ 618 (-13.81%)
Mutual labels:  validation
Intl Tel Input
A JavaScript plugin for entering and validating international telephone numbers
Stars: ✭ 5,963 (+731.66%)
Mutual labels:  validation
Pydantic
Data parsing and validation using Python type hints
Stars: ✭ 8,362 (+1066.25%)
Mutual labels:  validation
Vue Mc
Models and Collections for Vue
Stars: ✭ 588 (-17.99%)
Mutual labels:  validation
Go Proto Validators
Generate message validators from .proto annotations.
Stars: ✭ 713 (-0.56%)
Mutual labels:  validation
Vue Composable
Vue composition-api composable components. i18n, validation, pagination, fetch, etc. +50 different composables
Stars: ✭ 638 (-11.02%)
Mutual labels:  validation
Validatedpropertykit
Easily validate your Properties with Property Wrappers 👮
Stars: ✭ 701 (-2.23%)
Mutual labels:  validation
Ng2 Validation
angular2 validation
Stars: ✭ 622 (-13.25%)
Mutual labels:  validation
Validation
The most awesome validation engine ever created for PHP
Stars: ✭ 5,484 (+664.85%)
Mutual labels:  validation
Vuelidate
Simple, lightweight model-based validation for Vue.js
Stars: ✭ 6,186 (+762.76%)
Mutual labels:  validation
Meteor Astronomy
Model layer for Meteor
Stars: ✭ 608 (-15.2%)
Mutual labels:  validation
Formsy React
A form input builder and validator for React JS
Stars: ✭ 708 (-1.26%)
Mutual labels:  validation
Vvalidator
🤖 An easy to use form validator for Kotlin & Android.
Stars: ✭ 592 (-17.43%)
Mutual labels:  validation
Malli
Data-Driven Schemas for Clojure/Script.
Stars: ✭ 667 (-6.97%)
Mutual labels:  validation
Angular Validation
[INACTIVE] Client Side Validation for AngularJS 1. (You should use version > 2 💥)
Stars: ✭ 714 (-0.42%)
Mutual labels:  validation
Swagger Parser
Swagger 2.0 and OpenAPI 3.0 parser/validator
Stars: ✭ 710 (-0.98%)
Mutual labels:  validation
Envalid
Environment variable validation for Node.js
Stars: ✭ 684 (-4.6%)
Mutual labels:  validation

Spected

Validation Library

Spected is a low level validation library for validating objects against defined validation rules. Framework specific validation libraries can be built upon spected, leveraging the spected appraoch of separating the speciific input from any validation. Furthermore it can be used to verify the validity deeply nested objects, f.e. server side validation of data or client side validation of JSON objects. Spected can also be used to validate Form inputs etc.

Getting started

Install Spected via npm or yarn.

npm install --save spected

Use Case

Spected takes care of running your predicate functions against provided inputs, by separating the validation from the input. For example we would like to define a number of validation rules for two inputs, name and random.

const validationRules = {
  name: [
    [ isGreaterThan(5),
      `Minimum Name length of 6 is required.`
    ],
  ],
  random: [
    [ isGreaterThan(7), 'Minimum Random length of 8 is required.' ],
    [ hasCapitalLetter, 'Random should contain at least one uppercase letter.' ],
  ]
}

And imagine this is our input data.

const inputData = { name: 'abcdef', random: 'z'}

We would like to have a result that displays any possible errors.

Calling validate spected(validationRules, inputData) should return

{name: true,
 random: [
    'Minimum Random length of 8 is required.',
    'Random should contain at least one uppercase letter.'
]}

You can also pass in an array of items as an input and validate that all are valid. You need to write the appropriate function to handle any specific case.

const userSpec = [
  [
    items => all(isLengthGreaterThan(5), items),
    'Every item must have have at least 6 characters!'
  ]
]

const validationRules = {
  id: [[ notEmpty, notEmptyMsg('id') ]],
  users: userSpec,
}

const input = {
  id: 4,
  users: ['foobar', 'foobarbaz']
}

spected(validationRules, input)

Validating Dynamic Data

There are cases where a validation has to run against an unknown number of items. f.e. submitting a form with dynamic fields. These dynamic fields can be an array or as object keys.

const input = {
  id: 4,
  users: [
    {firstName: 'foobar', lastName: 'action'},
    {firstName: 'foo', lastName: 'bar'},
    {firstName: 'foobar', lastName: 'Action'},
  ]
}

All users need to run against the same spec.

const capitalLetterMsg = 'Capital Letter needed.'

const userSpec = {
  firstName: [[isLengthGreaterThan(5), minimumMsg('firstName', 6)]],
  lastName: [[hasCapitalLetter, capitalLetterMsg]],
}

As we're only dealing with functions, map over userSpec and run the predicates against every collection item.

const validationRules = {
  id: [[ notEmpty, notEmptyMsg('id') ]],
  users: map(always(userSpec)),
}

spected(validationRules, input)

In case of an object containing an unknown number of properties, the approach is the following.

const input = {
  id: 4,
  users: {
    one: {firstName: 'foobar', lastName: 'action'},
    two: {firstName: 'foo', lastName: 'bar'},
    three: {firstName: 'foobar', lastName: 'Action'},
  }
}

Spected can also work with functions instead of an [predFn, errorMsg] tuple array, which means one can specify a function that expects the input and then maps every rule to the object. Note: This example uses Ramda map, which expects the function as the first argument and then always returns the UserSpec for every property.

const validationRules = {
  id: [[ notEmpty, notEmptyMsg('id') ]],
  users: map(() => userSpec)),
}

How UserSpec is applied to every Object key is not spected specific, but can be freely implemented as needed.

Spected also accepts a function as an input, i.e. to simulate if a field would contain errors if empty.

const verify = validate(a => a, a => a)
const validationRules = {
  name: nameValidationRule,
}
const input = {name: 'foobarbaz'}
const result = verify(validationRules, key => key ? ({...input, [key]: ''}) : input)
deepEqual({name: ['Name should not be empty.']}, result)

Basic Example

import {
  compose,
  curry,
  head,
  isEmpty,
  length,
  not,
  prop,
} from 'ramda'

import spected from 'spected'

// predicates

const notEmpty = compose(not, isEmpty)
const hasCapitalLetter = a => /[A-Z]/.test(a)
const isGreaterThan = curry((len, a) => (a > len))
const isLengthGreaterThan = len => compose(isGreaterThan(len), prop('length'))


// error messages

const notEmptyMsg = field => `${field} should not be empty.`
const minimumMsg = (field, len) => `Minimum ${field} length of ${len} is required.`
const capitalLetterMsg = field => `${field} should contain at least one uppercase letter.`

// rules

const nameValidationRule = [[notEmpty, notEmptyMsg('Name')]]

const randomValidationRule = [
  [isLengthGreaterThan(2), minimumMsg('Random', 3)],
  [hasCapitalLetter, capitalLetterMsg('Random')],
]

const validationRules = {
  name: nameValidationRule,
  random: randomValidationRule,
}

spected(validationRules, {name: 'foo', random: 'Abcd'})
// {name: true, random: true}

Advanced

A spec can be composed of other specs, enabling to define deeply nested structures to validate against nested input. Let's see this in form of an example.

const locationSpec = {
    street: [...],
    city: [...],
    zip: [...],
    country: [...],
}

const userSpec = {
    userName: [...],
    lastName: [...],
    firstName: [...],
    location: locationSpec,
    settings: {
        profile: {
            design: {
                color: [...]
                background: [...],
            }
        }
    }
}   

Now we can validate against a deeply nested data structure.

Advanced Example

import {
  compose,
  indexOf,
  head,
  isEmpty,
  length,
  not,
} from 'ramda'

import spected from 'spected'

const colors = ['green', 'blue', 'red']
const notEmpty = compose(not, isEmpty)
const minLength = a => b => length(b) > a
const hasPresetColors = x => indexOf(x, colors) !== -1

// Messages

const notEmptyMsg = field => `${field} should not be empty.`
const minimumMsg = (field, len) => `Minimum ${field} length of ${len} is required.`

const spec = {
  id: [[notEmpty, notEmptyMsg('id')]],
  userName: [[notEmpty, notEmptyMsg('userName')], [minLength(5), minimumMsg('userName', 6)]],
  address: {
    street: [[notEmpty, notEmptyMsg('street')]],
  },
  settings: {
    profile: {
      design: {
        color: [[notEmpty, notEmptyMsg('color')], [hasPresetColors, 'Use defined colors']],
        background: [[notEmpty, notEmptyMsg('background')], [hasPresetColors, 'Use defined colors']],
      },
    },
  },
}

const input = {
  id: 1,
  userName: 'Random',
  address: {
    street: 'Foobar',
  },
  settings: {
    profile: {
      design: {
        color: 'green',
        background: 'blue',
      },
    },
  },
}

spected(spec, input)

/* {
      id: true,
      userName: true,
      address: {
        street: true,
      },
      settings: {
        profile: {
          design: {
            color: true,
            background: true,
          },
        },
      },
    }
*/

Custom Transformations

In case you want to change the way errors are displayed, you can use the low level validate function, which expects a success and a failure callback in addition to the rules and input.

import {validate} from 'spected'
const verify = validate(
    () => true, // always return true
    head // return first error message head = x => x[0]   
)
const spec = {
  name: [
    [isNotEmpty, 'Name should not be  empty.']
  ],
  random: [
    [isLengthGreaterThan(7), 'Minimum Random length of 8 is required.'],
    [hasCapitalLetter, 'Random should contain at least one uppercase letter.'],
  ]
}

const input = {name: 'foobar', random: 'r'}

verify(spec, input)

//  {
//      name: true,
//      random: 'Minimum Random length of 8 is required.',
//  }


Check the API documentation for further information.

Further Information

For a deeper understanding of the underlying ideas and concepts:

Form Validation As A Higher Order Component Pt.1

Credits

Written by A.Sharif

Contributions by

Paul Grenier

Emilio Srougo

Andrew Palm

Luca Barone

and many more.

Also very special thanks to everyone that has contributed documentation updates and fixes (this list will updated).

Original idea and support by Stefan Oestreicher

Documentation

API

License

MIT

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].