New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

async-validate

Package Overview
Dependencies
Maintainers
1
Versions
97
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

async-validate

Asynchronous validation for object properties.

  • 0.0.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
241
decreased by-37.4%
Maintainers
1
Weekly downloads
 
Created
Source

async-validate

Asynchronous validation for node.

Installation

npm install async-validate

Unit Tests

npm test

Usage

Basic usage involves defining a descriptor, assigning it to a schema and passing the object to be validated and a callback function to the validate method of the schema:

var schema = require('async-validate');
var descriptor = {
  name: {type: "string", required: true}
}
var validator = new schema(descriptor);
validator.validate({name: "muji"}, function(errors, fields) {
  if(errors) {
    // validation failed, errors is an array of all errors
    // fields is an object keyed by field name with an array of
    // errors per field
    return handleErrors(errors, fields);
  }
  // validation passed
});

Rules may be functions that perform validation. The signature for a validation function is:

function(rule, value, callback, values)
  • rule: The validation rule in the source descriptor that corresponds to the field name being validated. It is always assigned a field property with the name of the field being validated.
  • value: The value of the source object property being validated.
  • callback: A callback function to invoke once validation is complete. It expects to be passed an array of Error instances to indicate validation failure.
  • values: The source object that was passed to the validate method.
var schema = require('async-validate');
var ValidationError = schema.error;
var descriptor = {
  name: function(rule, value, callback, values) {
    var errors = [];
    if(!/^[a-z0-9]+$/.test(value)) {
      errors.push(
        new ValidationError(
          util.format("Field %s must be lowercase alphanumeric characters",
            rule.field)));
    }
    callback(errors);
  }
}
var validator = new schema(descriptor);
validator.validate({name: "Firstname"}, function(errors, fields) {
  if(errors) {
    return handleErrors(errors, fields);
  }
  // validation passed
});

It is often useful to test against multiple validation rules for a single field, to do so make the rule an array of objects, for example:

var descriptor = {
  email: [
    {type: "string", required: true, pattern: schema.pattern.email},
    function(rule, value, callback, values) {
      var errors = []; 
      // test if email address already exists in a database
      // and add a validation error to the errors array if it does
      callback(errors);
    }
  ]
}

Validate

The validate method has the signature:

function(source, [options], callback)
  • source: The object to validate - required.
  • options: An object describing processing options for the validation.
  • callback: A callback function to invoke when validation completes.

Options

  • first: Invoke callback when the first validation rule generates an error, no more validation rules are processed. If your validation involves multiple asynchronous calls (for example, database queries) and you only need the first error use this option.
  • single: Only ever return a single error typically used in conjunction with first when a validation rule could generate multiple errors.
  • keys: Specifies the keys on the source object to be validated. Use this option to validate fields in a determinate order or to validate a subset of the rules assigned to a schema.

Consider the rule:

{type: "string", required: true, min: 10, pattern: /^[^-].*$/}

When supplied with a source object such as {name: "-name"} the validation rule would generate two errors, as the pattern does not match and the string length is less then the required minimum length for the field.

In this instance when you only want the first error encountered use the single option.

Rules

Required

Add a required field to the rule to validate that the property exists.

Type

Add a type field to a rule to indicate that the field must be of the specified type. Recognised type values are:

  • string
  • number
  • boolean
  • regexp
  • integer
  • float
  • array
Pattern

The pattern field should be a valid RegExp to test the value against.

Minimum

When testing with a type of string the min property determines the minimum number of characters for the string.

When testing with a type of number the min property indicates the number may not be less than min.

Maximum

When testing with a type of string the max property determines the maximum number of characters for the string.

When testing with a type of number the max property indicates the number may not be greater than max.

Range

Combine the min and max properties to define a validation range.

Whitespace

It is typical to treat required fields that only contain whitespace as errors. To add an additional test for a string that consists solely of whitespace add a whitespace property to a rule with a value of true. The rule must be a string type.

Standard Rules

Some standard rules for common validation requirements are accessible via schema.rules.std. You may wish to reference these rules or copy and modify them.

Field

A typical required field:

{type: "string", required: true, whitespace: true}

Email

A basic email validation rule using a pattern:

{type: "string", required: true, pattern: pattern.email}

Note validating email addresses by regular expressions is fraught with pitfalls, use this with caution.

URL

A simple http(s) URL rule:

{type: "string", required: true, pattern: pattern.url}

Hex

A rule for hexadecimal color values with optional leading hash:

{type: "string", required: true, pattern: pattern.hex}

Keywords

FAQs

Package last updated on 24 Jun 2013

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc