# Objection JSON Model Validation

# Introduction

JSON schema (opens new window) validation can be enabled by setting the jsonSchema property of a model class. The validation is ran each time a Model instance is created.

You rarely need to call $validate method explicitly, but you can do it when needed. If validation fails a ValidationError will be thrown. Since we use Promises, this usually means that a promise will be rejected with an instance of ValidationError.

Let's add a validation to our UserModel

import { Model } from "Elucidate/Database/Model";

export class UserModel extends Model {
  static tableName = "users";

  id!: number;
  first_name!: string;
  last_name!: string;
  email!: string;
  password!: string;

  // Optional JSON schema. This is not the database schema! Nothing is generated
  // based on this. This is only used for validation. Whenever a model instance
  // is created it is checked against this schema. http://json-schema.org/.
  static jsonSchema = {
    type: "object",
    required: ["name"],

    properties: {
      id: { type: "integer" },
      first_name: { type: "string", minLength: 1, maxLength: 255 },
      last_name: { type: "string", minLength: 1, maxLength: 255 },
      email: { type: "string", minLength: 1, maxLength: 255 },
      password: { type: "string", minLength: 1, maxLength: 255 },
    },
  };
}

Visit ObjectionJs documentation site (opens new window) for more info.