Skip to content
Brian Donovan edited this page Aug 23, 2013 · 7 revisions

WikiAPI ReferenceValidatorBuilder

# LGTM.validator()

Creates a new ValidatorBuilder which can be used to build an ObjectValidator. This object uses the builder pattern and the method calls are intended to be chained. The result is intended to read more or less as a sentence -- a description of what the validator will do.

# builder.validates(attr)

This method sets the current attribute for subsequent calls to using() and when() and must be called before calls to either of those methods.

# builder.using(fn, message)

This method adds a validation to the underlying ObjectValidator for the current attribute wrapped by the current condition if one exists. fn must be a function that returns either true or false or a promise that resolves to true or false. message may be anything you want, but is generally an error message string you intend to present to the user. If the validation added by this call fails, message will be included in the validation results.

# builder.when(fn)

Use this to make subsequent calls to using() conditional. This method sets the current condition, modifying the behavior of subsequent calls to using() until either when() is called again to replace this condition or validates() is called to clear it. fn must be a function that returns either true or false or a promise that resolves to true or false. If the result of fn() is false (or resolves to false) then the validations chained after this call will not be called.

Helpers

Helpers provide shortcuts to commonly-used validations and conditions. All registered helpers are automatically available on ValidatorBuilder instances.

Core

# builder.required(message)

Adds a validation for the current attribute that will fail if the value of the validated attribute is absent (i.e. null, undefined, or an all-whitespace string).

# builder.optional()

Sets the condition for the current attribute's subsequent validations such that they will not be used unless the value to validate is present (i.e. not null, undefined, or an all-whitespace string).

# builder.email(message)

Adds a validation for the current attribute that will fail if the value of the validated attribute is not an email address. This validation is meant to be a good default but may allow email addresses you don't want. Remember that you can always override any built-in helper (see Custom Helpers).

# builder.minLength(length, message)

Adds a validation for the current attribute that will fail if the length of the value is less than the given length. This works for anything that has a .length property, such as strings and arrays.

# builder.maxLength(length, message)

See Custom Helpers for information on writing your own helpers.

Clone this wiki locally