All Projects → bvego → Nope Validator

bvego / Nope Validator

Licence: mit
A small, simple and fast JS validator. Like, wow thats fast. 🚀

Programming Languages

javascript
184084 projects - #8 most used programming language
typescript
32286 projects

Projects that are alternatives of or similar to Nope Validator

Framework
Strongly-typed JavaScript object with support for validation and error handling.
Stars: ✭ 136 (-4.23%)
Mutual labels:  object, schema, validation
Typet
Types that make coding in Python quick and safe.
Stars: ✭ 15 (-89.44%)
Mutual labels:  schema, validation
Mintype
🍵 minimal composable type abstraction
Stars: ✭ 12 (-91.55%)
Mutual labels:  schema, validation
Govalid
Data validation library for golang. [MIGRATING TO NEW ADDRESS]
Stars: ✭ 59 (-58.45%)
Mutual labels:  schema, validation
Forgjs
ForgJs is a javascript lightweight object validator. Go check the Quick start section and start coding with love
Stars: ✭ 1,687 (+1088.03%)
Mutual labels:  object, validation
Structured Acceptance Test
An open format definition for static analysis tools
Stars: ✭ 10 (-92.96%)
Mutual labels:  schema, validation
Inicpp
C++ parser of INI files with schema validation.
Stars: ✭ 47 (-66.9%)
Mutual labels:  schema, validation
Marshmallow
A lightweight library for converting complex objects to and from simple Python datatypes.
Stars: ✭ 5,857 (+4024.65%)
Mutual labels:  schema, validation
Ngx Dynamic Form Builder
FormBuilder + class-transformer + class-validator = dynamic form group builder for Angular10+
Stars: ✭ 93 (-34.51%)
Mutual labels:  object, validation
Pandasschema
A validation library for Pandas data frames using user-friendly schemas
Stars: ✭ 135 (-4.93%)
Mutual labels:  schema, validation
Postguard
🐛 Statically validate Postgres SQL queries in JS / TS code and derive schemas.
Stars: ✭ 104 (-26.76%)
Mutual labels:  schema, validation
Valley
Extensible schema validations and declarative syntax helpers in Python.
Stars: ✭ 25 (-82.39%)
Mutual labels:  schema, validation
Cafy
☕️ Simple, lightweight, flexible validator generator
Stars: ✭ 22 (-84.51%)
Mutual labels:  schema, validation
Strictyaml
Type-safe YAML parser and validator.
Stars: ✭ 836 (+488.73%)
Mutual labels:  schema, validation
Awesome Python Models
A curated list of awesome Python libraries, which implement models, schemas, serializers/deserializers, ODM's/ORM's, Active Records or similar patterns.
Stars: ✭ 124 (-12.68%)
Mutual labels:  schema, validation
Zaml
The Final Form of configuration files
Stars: ✭ 45 (-68.31%)
Mutual labels:  schema, validation
Superstruct
A simple and composable way to validate data in JavaScript (and TypeScript).
Stars: ✭ 5,604 (+3846.48%)
Mutual labels:  schema, validation
Meteor Astronomy
Model layer for Meteor
Stars: ✭ 608 (+328.17%)
Mutual labels:  schema, validation
Vue Rawmodel
RawModel.js plugin for Vue.js v2. Form validation has never been easier!
Stars: ✭ 79 (-44.37%)
Mutual labels:  schema, validation
Rdfunit
An RDF Unit Testing Suite
Stars: ✭ 117 (-17.61%)
Mutual labels:  schema, validation

Nope 🙅

codebeat badge CircleCI Fast Version size gzip FOSSA Status

A small, simple and fast JS validator. Like, wow thats fast. 🚀

Nope's API is heavily inspired stolen from Yup but Nope attempts to be much smaller and much faster. To achieve this Nope only allows for synchronous data validation which should cover most of the use cases.

Note: Nope is not a plug-and-play replacement for Yup, in some cases at least.

Instead of throwing errors Nope simply returns the error object and if there are no errors it returns undefined.

Typescript definitions included. ✨

Usage

To start using Nope simply do

yarn add nope-validator

or

npm install -S nope-validator
// const Nope = require('nope-validator'); // or
// const { Nope } = require('nope-validator'); // or
import Nope from 'nope-validator';
// create a schema

const UserSchema = Nope.object().shape({
  name: Nope.string()
    .atLeast(5, 'Please provide a longer name')
    .atMost(255, 'Name is too long!'),
  email: Nope.string()
    .email()
    .required(),
  confirmEmail: Nope.string()
    .oneOf([Nope.ref('email')])
    .requried(),
});

UserSchema.validate({
  name: 'John',
  email: '[email protected]',
  confirmEmail: '[email protected]',
}); // returns an error object { name: 'Please provide a longer name '};
UserSchema.validate({
  name: 'Jonathan Livingston',
  email: '[email protected]',
  confirmEmail: '[email protected]',
}); // returns undefined since there are no errors

API

  • Primitives (String, Number, Date, Boolean)

    • when(key: string | string[], conditionObject: { is: boolean | ((...args: any) => boolean), then: NopeSchema, othervise: NopeSchema }) - Conditional validation of a key.

    • The first param is the set of keys (or a single key) that the is predicate should run on.

    • The is param can be set to simply true or false (which will run the .every method on the values and assert the against the passed is) or a predicate that will decide what schema will be active in that moment.

    • const schema = Nope.object().shape({
        check: Nope.boolean().required(),
        test: Nope.string().when('check', {
          is: true,
          then: Nope.string()
            .atLeast(5, 'minError')
            .required(),
          otherwise: Nope.string()
            .atMost(5)
            .required(),
        }),
      });
      
      schema.validate({
        check: true,
        test: 'test',
      }); // { test: 'minError' }
      // or as a predicate
      const schema2 = Nope.object().shape({
        check: Nope.boolean(),
        check2: Nope.boolean(),
        test: Nope.string().when(['check', 'check2'], {
          is: (check, check2) => check && check2,
          then: Nope.string()
            .atLeast(5, 'minError')
            .required(),
          otherwise: Nope.string()
            .atMost(5)
            .required(),
        }),
      });
      schema.validate({
        check: true,
        check2: false,
        test: 'testing',
      }); // { test: 'maxError' }
      
    • oneOf(options: string | ref[], message: string) - Asserts if the entry is one of the defined options

    • Nope.string()
        .oneOf(['a', 'b', 'c'])
        .validate('b'); // returns undefined
      
      Nope.string()
        .oneOf(['a', 'b', 'c'])
        .validate('d'); // returns the error message
      
    • notOneOf(options: number | ref[], message: string) - Asserts if the entry is one of the defined options

    • Nope.string()
        .notOneOf([1, 2, 3])
        .validate(5); // returns undefined
      
      Nope.string()
        .notOneOf([1, 2, 3])
        .validate(2); // returns the error message
      
    • required(message: string) - Asserts if the entry is not nil

    • Nope.string()
        .required()
        .validate('b'); // returns undefined
      
      Nope.string()
        .required()
        .validate(); // returns the error message
      
    • test(rule: (entry: string) => string | undefined) - Add a custom rule

    • Nope.string()
        .test(a => (a === '42' ? undefined : 'Must be 42'))
        .validate('42'); // returns undefined
      
      Nope.string()
        .test(a => (a === '42' ? undefined : 'Must be 42'))
        .validate('41'); // returns the error message
      
    • validate(entry: string | undefined | null) - Runs the rule chain against an entry

  • Object

    • shape(shape: object) - Sets the shape which of the object. Use name as keys and Nope validators as values
    • const schema = Nope.object().shape({
        name: Nope.string()
          .atMost(15)
          .required(),
        email: Nope.string()
          .email('Please provide a valid email')
          .required(),
      });
      
      const errors = schema.validate({
        name: 'Test',
        email: 'invalidemail',
      });
      
      console.log(errors); // { email: 'Please provide a valid email', }
      
    • extend(Base: NopeObject) - Extends the schema of an already defined NopeObject
    • const baseSchema = Nope.object().shape({
        password: Nope.string().atLeast(5),
        confirmPassword: Nope.string()
          .oneOf([Nope.ref('password')], "Passwords don't match")
          .required(),
      });
      
      const userSchema = Nope.object()
        .extend(baseSchema)
        .shape({
          name: Nope.string()
            .atLeast(4)
            .required(),
        });
      
      userSchema.validate({
        name: 'Jonathan',
        password: 'birdybird',
        confirmPassworod: 'burdyburd',
      }); // returns { confirmPassword: 'Passwords don\'t match' }
      
  • String

    • regex(regex: RegExp, message: string) - Asserts if the entry matches the pattern

    • Nope.string()
        .regex(/abc/i)
        .validate('abc'); // returns undefined
      
      Nope.string()
        .regex(/abc/i)
        .validate('123'); // returns the error message
      
    • url(message: string) - Asserts if the entry is a valid URL

    • Nope.string()
        .url()
        .validate('http://google.com'); // returns undefined
      
      Nope.string()
        .url()
        .validate('http:google.com'); // returns the error message
      
    • email(message: string) - Asserts if the entry is a valid email

    • Nope.string()
        .email()
        .validate('[email protected]'); // returns undefined
      
      Nope.string()
        .email()
        .validate('testgmail.com'); // returns the error message
      
    • min(length: number, message: string) - deprecated: alias for greaterThan

    • max(length: number, message: string) - deprecated: alias for lessThan

    • greaterThan(length: number, message: string) - Asserts if the entry is smaller than a threshold

    • Nope.string()
        .greaterThan(4)
        .validate('https'); // returns undefined
      
      Nope.string()
        .greaterThan(4)
        .validate('http'); // returns the error message
      
    • lessThan(length: number, message: string) - Asserts if the entry is greater than a threshold

    • Nope.string()
        .lessThan(4)
        .validate('url'); // returns undefined
      
      Nope.string()
        .lessThan(4)
        .validate('http'); // returns the error message
      
      
    • exactLength(length: number, message: string) - Asserts if the entry is of exact length

    • Nope.string()
        .exactLength(4)
        .validate('test'); // returns undefined
      
      Nope.string()
        .exactLength(4)
        .validate('testing'); // returns the error message
      
  • Number

    • integer(message: string) - Asserts if the entry is an integer

    • Nope.number()
        .integer('error message')
        .validate(2); // returns undefined
      
      Nope.number()
        .integer('error message')
        .validate(4.2); // returns the error message
      
    • min(size: number, message: string) - deprecated: alias for greaterThan

    • max(size: number, message: string) - deprecated: alias for lessThan

    • greaterThan(size: number, message: string) - Asserts if the entry is smaller than a threshold

    • Nope.number()
        .greaterThan(1, 'error message')
        .validate(2); // returns undefined
      
      Nope.number()
        .greaterThan(1, 'error message')
        .validate(1); // returns the error message
      
    • lessThan(size: number, message: string) - Asserts if the entry is greater than a threshold

    • Nope.number()
        .lessThan(1, 'error message')
        .validate(-1); // returns undefined
      
      Nope.number()
        .lessThan(1, 'error message')
        .validate(2); // returns the error message
      
    • positive(message: string) - Asserts if the entry is positive

    • Nope.number()
        .positive('error message')
        .validate(42); // returns undefined
      
      Nope.number()
        .positive('error message')
        .validate(-42); // returns the error message
      
    • negative(message: string) - Asserts if the entry is negative

    • Nope.number()
        .negative('error message')
        .validate(-42); // returns undefined
      
      Nope.number()
        .negative('error message')
        .validate(42); // returns the error message
      
  • Date

    • before(date: string | number | Date, message: string) - Asserts if the entry is before a certain date

    • Nope.date()
        .before('2019-01-01')
        .validate('2018-31-12'); // returns undefined
      
      Nope.date()
        .before('2019-01-01')
        .validate('2019-01-02'); // returns the error message
      
    • after(date: string | number | Date, message: string) - Asserts if the entry is after a certain date

    • Nope.date()
        .after('2019-01-01')
        .validate('2018-02-01'); // returns undefined
      
      Nope.date()
        .after('2019-01-01')
        .validate('2018-31-12'); // returns the error message
      
  • Boolean

    • true(message: string) - Asserts if the entry is true

    • Nope.boolean()
        .true()
        .validate(true); // returns undefined
      
      Nope.boolean()
        .true()
        .validate(false); // returns the error message
      
    • false(message: string) - Asserts if the entry is false

    • Nope.boolean()
        .false()
        .validate(false); // returns undefined
      
      Nope.boolean()
        .false()
        .validate(true); // returns the error message
      
    • noUnknown(message: string) - Return an error message if the entry contains keys that are not defined in the schema

    • const schema = Nope.object().shape({
        name: Nope.string().atLeast(5),
      }).noUnknown('no unknown keys');
      
      schema.validate({
        name: 'Jonathan',
        password: 'birdybird',
      }); // returns 'no unknown keys';
      
    • validate(entry: object) - Runs the rule chain against an entry

    • validateAt(path: string, entry: Record<string | number, any>)

    • const schema = Nope.object().shape({
          foo: Nope.array().of(
            Nope.object().shape({
              loose: Nope.boolean(),
              bar: Nope.string().when('loose', {
                is: true,
                then: Nope.string().max(5, 'tooLong'),
                otherwise: Nope.string().min(5, 'tooShort'),
              }),
            }),
          ),
        });
      
        const rootValue = {
          foo: [{ bar: '123' }, { bar: '123456', loose: true }],
        };
      
        schema.validateAt('foo[0].bar', rootValue); // returns 'tooShort';
        schema.validateAt('foo[1].bar', rootValue); // returns 'tooLong';
      
  • Array

    • required(message: string) - Required field (non falsy)
    • of(primitive: Validatable<T>) - Required the field to be of a certain schema
    • const schema = Nope.object().shape({
        names: Nope.array()
          .of(Nope.string().min(5))
          .required(),
      });
      
      schema.validate({
        names: ['Geralt']
      }); // returns undefined;
      
    • minLength(length: number, message?: string) - Minimal length of the field
    • maxLength(length: number, message?: string) - Max length of the field
    • mustContain(value: T, message?: string) - Must contain a certain item
    • hasOnly(values: T[], message?: string) - Must only contain certain items
    • every(predicate: item => boolean, message?: string) - Every item passes predicate. Alike Array.prototype.every
    • some(predicate: item => boolean, message?: string) - Some items pass the predicate. Alike Array.prorotype.some
  • Reference - allows the schema to reference other values in the provided entry

    • const schema = Nope.object().shape({
        email: Nope.string()
          .email()
          .atMost(255)
          .required(),
        confirmEmail: Nope.string().oneOf([Nope.ref('email')], 'Must match the first email'),
      });
      
      const errors = schema.validate({
        email: '[email protected]',
        confirmEmail: '[email protected]',
      });
      console.log(errors); // { confirmEmail: 'Must match the first email' }
      
      const noerrors = schema.validate({
        email: '[email protected]',
        confirmEmail: '[email protected]',
      });
      
      console.log(noerrors); // undefined
      

Usage with Formik

Instead of passing it through the validationSchema prop, you should call Nope's validate on the validate prop as shown in the example below.

const schema = Nope.object().shape({
  email: Nope.string()
    .email()
    .atMost(255)
    .required(),
  password: Nope.string()
    .atLeast(8)
    .atMost(64)
    .required(),
});

<Formik
  initialValues={{ email: '', password: '' }}
  validate={values => schema.validate(values)}
  onSubmit={values => console.log('Submitted', values)}
>
  {() => (
    <Form>
      <Field type="email" name="email" />
      <ErrorMessage name="email" component="div" />
      <Field type="password" name="password" />
      <ErrorMessage name="password" component="div" />
      <button type="submit">Submit</button>
    </Form>
  )}
</Formik>;

License

FOSSA Status

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].