- validated-attributes
- Usage
- Base Classes
- Simple Attribute Classes
- Combined Attribute Classes
- Functions
- ValidatorFn
- DefaultValue
- ElementValidatorFn
- ElementIterator
- DetailedType
Beta-quality declarative attributes validation library for JavaScript.
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.
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(),
});
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
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
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.
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.
Extends ExtendableError
Error class for validation errors
You might want to test a thrown error with instanceof
against this class.
Base class for attributes
You can inherit from this class to create custom validators; you must override
at least the _clone
method.
-
validator
ValidatorFn -
defaultsTo
DefaultValue?
Name of the attribute; usually reflects its type
Type: string
Arbitrary flags you can use for your application purposes
Type: {}
Default value of the attribute (function that creates a default or immutable value)
Type: DefaultValue
Whether this attribute is marked as optional; changes behavior of validate and newSkeleton
Type: boolean
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.
-
input
any
Returns any
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
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 (!)
-
value
any -
nullIsUndefined
boolean?
Returns any
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
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.
-
newDefault
DefaultValue
Returns this
Adds one or more boolean flags
Same as calling with({'flag1': true, 'flag2': true, ...})
.
Clones the attribute object.
Returns this
Adds one or more arbitrary flags
Clones the attribute object.
-
flags
{}
Returns this
Turns the attribute optional
Clones the attribute object.
Returns this
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
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
.
-
source
Attribute
Returns this
Extends Attribute
Represents a simple fixed value attribute
The comparison is done with the === operator.
-
value
any
The fixed value itself
Type: any
Type of the fixed value
Type: string
Clone the attribute
Overrides base implementation
Returns FixedAttribute
Extends Attribute
Represents an instanceOf-attribute
The class is instantiated with an empty constructor as default.
-
Cls
any
Class object
Type: any
Clone the attribute
Overrides base implementation
Returns ObjectAttribute
Extends Attribute
Represents an oneOf-attribute
The first value is used to generate the default.
-
values
Array<any>
List of valid attributes for this enum
Clone the attribute
Overrides base implementation
Returns EnumAttribute
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.
-
selements
Array<any>
Array of attributes to validate the tuple's contents against
Main method for validation
Extends base implementation
-
input
any
Returns any
Merges the given value with the default of this attribute
Overrides base implementation
-
value
any -
nullIsUndefined
boolean?
Returns any
Returns a new skeleton for this attribute
Overrides base implementation
Returns Array<any>?
Clone the attribute
Overrides base implementation
Returns TupleAttribute
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.
-
validator
ValidatorFn -
skeletonMaker
function (): any -
iterator
ElementIterator
Attribute that all elements must have
Type: Attribute?
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.
-
spec
any
Returns this
Main method for validation
Extends base implementation
-
input
any
Returns any
Returns a new skeleton for this attribute
Overrides base implementation
Clone the attribute
Overrides base implementation
Returns CompoundAttribute
Copies the attribute's properties
Extends base implementation
-
source
Attribute
Returns this
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.
-
sfields
{}
Fields to validate
Type: {}
Main method for validation
Extends base implementation
-
input
any
Returns any
Merges the given value with the default of this attribute
Overrides base implementation
-
value
any -
nullIsUndefined
boolean?
Returns any
Returns a new skeleton for this attribute
Overrides base implementation
Clone the attribute
Overrides base implementation
Returns SchemaAttribute
Short-cut to run a validation of the given specification against the given value
-
spec
any -
value
any
Returns any
Tests a value against a specification
Returns true or false rather than trowing an exception
-
spec
any -
value
any
Returns boolean
Short-cut to create a default value for the given specification
-
spec
any
Returns any
Short-cut to merge the given value into the given specification, filling up missing values with default values
-
spec
any -
value
any -
nullIsUndefined
boolean?
Returns any
Short-cut to create a skeleton from the given specification
-
spec
any
Returns any
Converts a fixed value or tuple or schema to the respective Attribute object
-
v
any
Returns Attribute
A more detailed version of the typeof
operator
-
x
any
Returns DetailedType
Type: function (input: any): boolean
Type: (function (): any | any)
Type: function (element: any, index: (number | string)): void
Type: function (input: any, elementValidator: ElementValidatorFn): void
Result of typeofPlus
Type: ("undefined"
| "number"
| "boolean"
| "string"
| "function"
| "regexp"
| "array"
| "date"
| "error"
| "null"
| "symbol"
| "object"
)