1

I'm pretty new to Loopback 4 framework, and I'm trying to use it for a small project that needs to connect data from different kinds of databases and services. One of the main reasons I'm using version 4 is because of Typescript and also because it supports ES7 features (async/await), which I really appreciate. Still, I have no idea how to implement model validation, at least not like Loopback v3 supports.

I've tried to implement custom validation on model constructors, but it looks like a really bad pattern to follow.

import {Entity, model, property} from '@loopback/repository';

@model()
export class Person extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
  })
  id: number;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @property({
    type: 'date',
    required: true,
  })
  birthDate: string;

  @property({
    type: 'number',
    required: true,
  })
  phone: number;

  constructor(data: Partial<Person>) {
    if (data.phone.toString().length > 10) throw new Error('Phone is not a valid number');
    super(data);
  }
}

1 Answers1

2

LB4 uses ajv module to validate the incoming request data based on your model metadata. So, you can do a it using jsonSchema as mentioned below.

export class Person extends Entity {
  @property({
    type: 'number',
    id: true,
    required: true,
  })
  id: number;

  @property({
    type: 'string',
    required: true,
  })
  name: string;

  @property({
    type: 'date',
    required: true,
  })
  birthDate: string;

  @property({
    type: 'number',
    required: true,
    jsonSchema: {
      maximum: 9999999999,
    },
  })
  phone: number;

  constructor(data: Partial<Person>) {
    super(data);
  }
}

Hope that works. Refer to the answer to a similar question on LB4 repo here for more details.

Samarpan
  • 913
  • 5
  • 12
  • 1
    Thanks Samy! It really helped me a lot! Now I'm stuck with custom validation, this cpf property is an ID with a custom validation rule (its basically an ID that the Brazilian government gives you, similar to US IDs). Any ideas on how to add keywords on Ajv module? I tried to follow these instructions (https://github.com/epoberezkin/ajv/blob/master/CUSTOM.md), importing the Ajv module on the model file. – Gustavo Leme Apr 22 '19 at 18:49
  • If you can share the code you are trying with (in a repo or stackblitz), I may be able to help you better. As far as I can see, ajv keywords should work. – Samarpan Apr 23 '19 at 05:41
  • Did you try with 'pattern' in jsonSchema ? – Samarpan Apr 23 '19 at 05:53
  • How do you implement validation rules that can't be expressed using JSON Schema? – Paul D. Waite Sep 10 '19 at 16:49
  • I do it at controller method. – Samarpan Oct 02 '19 at 03:03
  • Answer is slightly incorrect, should be maximum: 9999999999 – Boštjan Pišler Oct 05 '22 at 08:14