validate

Validate object properties in javascript.

validate

Validate object properties in javascript.

var schema = require('validate');
var user = schema({
  name: {
    type: 'string',
    required: true,
    message: 'name is required'
  },
  email: {
    type: 'string',
    required: true,
    match: /+\@.+\..+/,
    message: 'email must be valid'
  },
  address: {
    street: {
      type: 'string',
      required: true
    },
    city: {
      type: 'string',
      required: true
    }
  },
});
  
var errors = user.validate(obj);

You can also add paths to a schema by using the chainable API

user
  .path('username')
  .type('string')
  .required()
  .match(/[a-z]{2,16}/)
  .message('username must be 2-16 chars');
 
user
  .path('address.zip')
  .type('string')
  .required()
  .match(/[0-9]+/)
  .message('zip is required');

Values can be automatically typecasted before validation. To enable typecasting, pass an options object to the schema constructor with typecast set to true. You can override this setting by passing options to .validate()

var user = schema({
  name: { type: 'string' },
  age: { type: 'number' }
}, { typecast: true });

To override

user.validate(obj, { typecast: false });

By default, all values not defined in the schema will be stripped from the object. Set .strip = false on the options object to disable this behavior.

Creates a new Schema with the given paths.

Add path to schema with optional rules. Returns a Property.

Validate given object. Returns an array of error messages.

Validate given object and throw if the validation fails.

Use the given validation function with and optional error message. fn should accept a value and return true if the value is considered valid.

Property should be of type name.

Property is required.

Proprety should match given regexp.

Validate each value in array against given function fn.

Set default error message for property.

MIT