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?

  1. Validation

Nested validations

Structure will validate nested values, including array items validations and nested structures.

const Book = attributes({
  name: {
    type: String,
    required: true,
  },
})(class Book {});

const User = attributes({
  initials: {
    type: String,
    minLength: 2,
  },
  favoriteBook: Book,
  books: {
    type: Array,
    itemType: Book,
  },
})(class User {});

const user = new User({
  initials: 'A',
  favoriteBook: new Book(),
  books: [new Book()],
});

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

valid; // false
errors; /*
[
  { message: '"initials" length must be at least 2 characters long', path: ['initials'] },
  { message: '"favoriteBook.name" is required', path: ['favoriteBook', 'name'] },
  { message: '"books[0].name" is required', path: ['books', 0, 'name'] }
]
*/
PreviousAttribute referenceNextValidate raw data

Last updated 4 years ago

Was this helpful?