Structure
Structure v2
Structure v2
  • Introduction
  • Schema concept
    • Shorthand and complete attribute definition
    • Circular reference
    • Nullable attributes
  • Custom setters and getters
  • Coercion
    • Primitive type coercion
    • Arrays coercion
    • Generic coercion
    • Recursive coercion
    • Disabling coercion
  • Validation
    • String validations
    • Number validations
    • Boolean validations
    • Date validations
    • Array validations
    • Attribute reference
    • Nested validations
    • Validate raw data
  • Strict mode
  • Cloning an instance
  • Serialization
  • Testing
  • Battlecry generators
  • Migrating from v1
  • Support and compatibility
  • Changelog
  • Contributing
  • License
  • GitHub
Powered by GitBook
On this page

Was this helpful?

Validation

A validate() method will be added to the prototype of structures, this method will validate the structure based on its schema. The method will return an object with the property valid (with the value true if it's valid, and false if invalid). If valid is false the returned object will also have a property errors, with an array of validation errors.

Validations require you to use the complete attribute definition:

const User = attributes({
  name: {
    type: String,
    minLength: 10,
  },
  age: {
    type: Number,
    required: true,
  },
})(class User {});

const user = new User({
  name: 'John',
});

const { valid, errors } = user.validate();

valid; // false
errors; /*
[
  { message: '"name" length must be at least 10 characters long', path: ['name'] },
  { message: '"age" is required', path: ['age'] }
]
*/

const validUser = new User({
  name: 'This is my name',
  age: 25,
});

const validation = validUser.validate();

validation.valid; // true
validation.errors; // undefined, because `valid` is true

Observations

PreviousDisabling coercionNextString validations

Last updated 4 years ago

Was this helpful?

Structure has a set of built-in validations built on top of the awesome package:

Validations marked with * accept a value, an , or an array of values and attribute references mixed.

Validations marked with ** accept a value or an .

joi
attribute reference
attribute reference