README
Table of Contents
- validated-attributes
- Usage
- Base Classes
- Simple Attribute Classes
- Combined Attribute Classes
- Functions
- ValidatorFn
- DefaultValue
- ElementValidatorFn
- ElementIterator
- DetailedType
validated-attributes
Beta-quality declarative attributes validation library for JavaScript.
Usage
The intended way of using this library is through importing it as A
and then
using it declaratively. Like this, things will almost form a readable sentence.
After creating the Attribute objects, a call to .validate(something)
will do
the job; an error is thrown on failure or the value is returned as-is on
success. The error can be inspected for your program logic to create appropriate
error messages towards the user. Should you only require a boolean value if the
validation succeeded, the isValid()
helper function can be used.
The greatest power of this library is the way things can be re-used and combined, which is most useful for schema attributes. See the example below.
Example
import A from 'validated-attributes';
const Address = A.schema({
street: A.required.string,
city: A.required.string,
zip: A.required.string,
country: A.required.string,
state: A.optional.string,
});
const User = A.schema({
firstName: A.required.string,
lastName: A.required.string,
email: A.required.string,
privateAddress: Address,
bizAddress: Address.makeOptional(),
});
List of Pre-Defined Objects
All of the following can be used directly, i.e. A.<name>
. or by prepending
"required", i.e. A.required.<name>
, which is just for readability. In addition
to that, the objects can be found in an optional variant A.optional.<name>
which is most useful in schema Attributes. At any time, a required Attribute can
be turned into an optional Attribute by calling .makeOptional()
, but note that
this will create a new object each time.
A.string - Any string value
A.nonemptyString - Any string that is not the empty string
A.integerString - A string that consists of integer digits
A.uuid - A string that represents an UUID (uses a RegExp)
A.email - A string that represents an eMail address (uses a "close enough" RegExp)
A.dateString - A string that represents a date in the form YYYY-MM-DD (uses a RegExp followed by Date.parse)
A.boolean - Any boolean value
A.number - Any number value
A.integer - An integer number value
A.regexp - Any RegExp object
A.date - Any date object
A.function - Any function object
A.array - Any array value; can be customized, see CompoundAttribute.ofType
A.map - Any object with values; can be customized, see CompoundAttribute.ofType
List of Factory Functions
The following can also be used directly, as required and as optional, but rather than being a fixed value, they are in fact functions that create an Attribute object.
A.fixed(v) - A fixed value, checked by ===
A.tuple(elements) - A fixed-length array with elements of the given Attribute type
A.schema(fields) - A plain object with the given Attribute fields
A.instanceOf(cls) - An object of a specific class
A.oneOf(...args) - The value can be a selection of Attributes; at least one should validate
Defaults
Each Attribute object can produce a default value, that can be overridden by
calling defaultsTo()
on the Attribute object. This will create a copy of the
Attribute object with the new default value set.
Either newDefault()
or mergeDefault()
can be used to produce a default
value. Compound Attribute objects will call this recursively on their inner
Attribute objects.
Skeletons
In addition to a default value, a so-called skeleton value can be obtained
from an Attribute object. In almost all cases, this will return a null
value,
but e.g. schema attributes will return an object with all fields set to either
null
or - if a field is schema Attribute itself - a skeleton of the respective
type.
Base Classes
AttributeValidationError
Extends ExtendableError
Error class for validation errors
You might want to test a thrown error with instanceof
against this class.
Parameters
Attribute
Base class for attributes
You can inherit from this class to create custom validators; you must override
at least the _clone
method.
Parameters
validator
ValidatorFndefaultsTo
DefaultValue?
name
Name of the attribute; usually reflects its type
Type: string
flags
Arbitrary flags you can use for your application purposes
Type: {}
default
Default value of the attribute (function that creates a default or immutable value)
Type: DefaultValue
isOptional
Whether this attribute is marked as optional; changes behavior of validate and newSkeleton
Type: boolean
validate
Main method for validation
Throws AttributeValidationError
on, you guessed it, validation errors.
Returns the validated object on success.
The default implementation calls the underlying validator function
Note: for use with flow type, cast the returned object to your target type.
Parameters
input
any
Returns any
newDefault
Creates a new default value for this attribute
Returns the value set with defaultsTo
or, if it is a function, invokes
it and returns its result.
Returns any
mergeDefault
Merges the given value with the default of this attribute
Optionally treats null
as undefined
even for optional attributes.
Works best for schema or tuple attributes since it works recursively; it will also remove any fields that are not specified in the schema (!)
Parameters
value
anynullIsUndefined
boolean?
Returns any
newSkeleton
Returns a new skeleton for this attribute
This is most useful for schema or compound attributes, where it will emit an object or array whose fields are set to null or which is empty.
Returns any
defaultsTo
Sets the attributes default value
The default can be a (immutable) value or a function creating a value. The latter is recommended if the value is something mutable, like an array or object.
Clones the attribute object.
Parameters
newDefault
DefaultValue
Returns this
as
Adds one or more boolean flags
Same as calling with({'flag1': true, 'flag2': true, ...})
.
Clones the attribute object.
Parameters
Returns this
with
Adds one or more arbitrary flags
Clones the attribute object.
Parameters
flags
{}
Returns this
makeOptional
Turns the attribute optional
Clones the attribute object.
Returns this
_clone
Internal method to clone an attribute object
Subclasses must override this method, and call _copyAttrProps
on the new
instance. Do not call the base implementation.
Returns Attribute
_copyAttrProps
Internal method that copies internal properties from the given attribute to this attribute
Used by _clone
. Subclasses must call the base implementation before copying
their own properties.
The base implementation copies the name, isOptional, default and flags
(as shallow copy). Returns this
.
Parameters
source
Attribute
Returns this
Simple Attribute Classes
FixedAttribute
Extends Attribute
Represents a simple fixed value attribute
The comparison is done with the === operator.
Parameters
value
any
value
The fixed value itself
Type: any
valueType
Type of the fixed value
Type: string
_clone
Clone the attribute
Overrides base implementation
Returns FixedAttribute
ObjectAttribute
Extends Attribute
Represents an instanceOf-attribute
The class is instantiated with an empty constructor as default.
Parameters
Cls
any
cls
Class object
Type: any
_clone
Clone the attribute
Overrides base implementation
Returns ObjectAttribute
Combined Attribute Classes
EnumAttribute
Extends Attribute
Represents an oneOf-attribute
The first value is used to generate the default.
Parameters
values
Array<any>
values
List of valid attributes for this enum
_clone
Clone the attribute
Overrides base implementation
Returns EnumAttribute
TupleAttribute
Extends Attribute
Represents an array attribute with fixed number and type of entries
The default value is an array with default values of each type. The skeleton
is either null
for optional tuples or an array with all values set to the
skeleton of each type.
Parameters
selements
Array<any>
elements
Array of attributes to validate the tuple's contents against
validate
Main method for validation
Extends base implementation
Parameters
input
any
Returns any
mergeDefault
Merges the given value with the default of this attribute
Overrides base implementation
Parameters
value
anynullIsUndefined
boolean?
Returns any
newSkeleton
Returns a new skeleton for this attribute
Overrides base implementation
Returns Array<any>?
_clone
Clone the attribute
Overrides base implementation
Returns TupleAttribute
CompoundAttribute
Extends Attribute
Represents array and map attributes
Optionally the values can be type-checked as well. Use ofType
for this.
If the attribute is marked as optional, newSkeleton
will return null.
Otherwise it creates an empty array or map.
Parameters
validator
ValidatorFnskeletonMaker
function (): anyiterator
ElementIterator
elementAttr
Attribute that all elements must have
Type: Attribute?
ofType
Bind a type to the contents of the compound attribute
All values of the compound will be validated against the given attribute.
Clones the attribute object.
Parameters
spec
any
Returns this
validate
Main method for validation
Extends base implementation
Parameters
input
any
Returns any
newSkeleton
Returns a new skeleton for this attribute
Overrides base implementation
_clone
Clone the attribute
Overrides base implementation
Returns CompoundAttribute
_copyAttrProps
Copies the attribute's properties
Extends base implementation
Parameters
source
Attribute
Returns this
SchemaAttribute
Extends Attribute
Represents a (plain) object attribute with fields of given types
The default value is an object with default values of each type for each field.
The skeleton is either null
for optional schemas or an object with all values
set to the skeleton of each type.
Parameters
sfields
{}
fields
Fields to validate
Type: {}
validate
Main method for validation
Extends base implementation
Parameters
input
any
Returns any
mergeDefault
Merges the given value with the default of this attribute
Overrides base implementation
Parameters
value
anynullIsUndefined
boolean?
Returns any
newSkeleton
Returns a new skeleton for this attribute
Overrides base implementation
_clone
Clone the attribute
Overrides base implementation
Returns SchemaAttribute
Functions
validate
Short-cut to run a validation of the given specification against the given value
Parameters
spec
anyvalue
any
Returns any
isValid
Tests a value against a specification
Returns true or false rather than trowing an exception
Parameters
spec
anyvalue
any
Returns boolean
newDefault
Short-cut to create a default value for the given specification
Parameters
spec
any
Returns any
mergeDefault
Short-cut to merge the given value into the given specification, filling up missing values with default values
Parameters
spec
anyvalue
anynullIsUndefined
boolean?
Returns any
newSkeleton
Short-cut to create a skeleton from the given specification
Parameters
spec
any
Returns any
toAttribute
Converts a fixed value or tuple or schema to the respective Attribute object
Parameters
v
any
Returns Attribute
typeofPlus
A more detailed version of the typeof
operator
Parameters
x
any
Returns DetailedType
ValidatorFn
Type: function (input: any): boolean
DefaultValue
Type: (function (): any | any)
ElementValidatorFn
Type: function (element: any, index: (number | string)): void
ElementIterator
Type: function (input: any, elementValidator: ElementValidatorFn): void
DetailedType
Result of typeofPlus
Type: ("undefined"
| "number"
| "boolean"
| "string"
| "function"
| "regexp"
| "array"
| "date"
| "error"
| "null"
| "symbol"
| "object"
)