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

Validate raw data

PreviousNested validationsNextStrict mode

Last updated 4 years ago

Was this helpful?

In addition to the instance validate() method, Structure also adds a static validate() to your structure classes that receives a raw object or a structure instance as parameter and has the same return type of the :

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

// Using a raw object
const rawData = {
  name: 'John',
};

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

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

// Using a structure instance
const user = new User({
  name: 'Some long name',
});

const validation = User.validate(user);

validation.valid; // false
validation.errors; /*
[
  { message: '"age" is required', path: ['age'] }
]
*/
normal validation