Is there any way to validate Loopback 4 Model,
Now i'm validate my model like this.
import {Entity, model, property, belongsTo} from '@loopback/repository';
import {SaleStore} from './sale-store.model';
import {VehicleQuarry} from '../patterns/vehicle-decorator';
import {UploadImages} from './upload-images.model';
@model()
export class Vehicle extends Entity {
@property({
type: 'number',
id: true,
index: true,
generated: true,
})
id?: number;
@property({
type: 'number',
})
vehicle_price?: number;
@property({
type: 'number',
})
vehicle_booking_price?: number;
// 1st -- i want to add more validations like, minimum price, maximum price
constructor(data?: Partial
super(data);
}
}
1st -- I want to add more validations like, I want to check minimum price, maximum price.
2nd-- Is there any way to compare two fields in model. like :
vehicle_booking_price < vehicle_price;
@DilupaSampath Model validation has different levels:
1st -- I want to add more validations like, I want to check minimum price, maximum price.
This could be achieved by the spec level validation.
We use ajv module to validate the incoming request data based on your model metadata, see document.
To specify a maximum/maxLength or minimum/minLength for your property, you can decorate the model property with a jsonSchema that contains valid keywords:
@model()
export class Vehicle extends Entity {
...
@Property({
type: 'number',
jsonSchema: {
maximum: 10,
minimum: 3,
}
})
vehicle_price?: number;
...
}
2nd-- Is there any way to compare two fields in model. like :
This would be a customized validation we haven't fully supported yet, you can follow the discussion and proposal from @bajtos in issue https://github.com/strongloop/loopback-next/issues/1872
thank you @jannyHou, 'ajv module' is good solution for my issue.Also I can handle my second question(2nd-- Is there any way to compare two fields in model.) using 'ajv module'.
Is there any way to enforce uniqueness like how mongodb does it in the model with unique:true
Most helpful comment
Is there any way to enforce uniqueness like how mongodb does it in the model with unique:true