Search code examples
javascriptloopback

How to specify minimum and maximum length for fields in Loopback 4?


I have defined the property in my model as follows:

@property({
    type: 'string',
    required: true,
    min: 2,
    max: 255
})
name: string

However, when I send the field consisting of 1 character, it didn't throw me the error. Can anybody help me on this?


Solution

  • Loopback 4 (as well as Loopback 3) does not support min/max properties by default and would not use it for validation of the data you send to the API. You can see the list of supported property properties in the documentation for Loopback 3 as nothing has changed in Loopback 4.

    Below is a statement from the Loopback 4 documentation:

    The data from request body is validated against its OpenAPI schema specification. We use AJV module to perform the validation, which validates data with a JSON schema generated from the OpenAPI schema specification.

    From Open API V3 documentation we can see they support string data type and

    String length can be restricted using minLength and maxLength:

    AJV support minLength and maxLength properties too, but for some reason, Loopback 4 does not have an easy, builtin way to define these properties with the @property decorator yet.

    Anyway, I found a workaround which you can use for now:

    import { Entity, model, property, Model } from '@loopback/repository';
    import { getJsonSchema } from '@loopback/repository-json-schema';
    
    @model()
    export class MyModel extends Model {
      @property({
        type: 'string',
        required: true,
      })
      name: string;
    
      constructor(data?: Partial<MyModel>) {
        super(data);
      }
    
      static initialize() {
        let jsonSchema = getJsonSchema(MyModel) as any;
        jsonSchema.properties.name.minLength = 2;
        jsonSchema.properties.name.maxLength = 255;
      }
    }
    
    MyModel.initialize();
    

    Note, all the magic happens in the MyModel.initialize method where I initialize jsonSchema using a standard getJsonSchema function (part of loopback). Then I extend this jsonSchema with additional minLength and maxLength properties. Inside of the getJsonSchema function they use a cache for json schemas, so the schema is generated just once for every model during the application lifecicle which ensures the values we set will stay there every time this json schema is requested later.

    You can also see related issues on the Loopback Next's Github page:

    Hopefully, they will support these types of validations as well as custom validators natively in Loopback decorators at some point.