An example application to demonstrate validation in LoopBack.
This application shows how to add validation in a LoopBack application. It
exposes /coffee-shops endpoints to create/read/update/delete a CoffeeShop
instance with the in-memory storage.
-
CoffeeShop model: Shows how to add validation using AJV.
Example to limit length on a string:
@property({ type: 'string', required: true, // Add jsonSchema jsonSchema: { maxLength: 10, minLength: 5, errorMessage: 'City name should be between 5 and 10 characters', }, }) city: string;
-
ValidatePhoneNumInterceptor: an interceptor for custom validation - it checks whether the area code of the phone number matches with the city name.
-
CoffeeShopController: controller where the
ValidatePhoneNumInterceptoris applied. -
MySequence: a custom sequence for creating custom error messages. This is not a requirement, just a demonstration of how to customize error messages during runtime.
Start the app:
npm startThe application will listen on port 3000. Open http://localhost:3000/explorer in
your browser. You can try to test the validation for the /coffee-shops
endpoints.
When calling POST /coffee-shops API, there are a few ways to test validation
is happening. An example of valid request body for CoffeeShop is:
{
"city": "Toronto",
"phoneNum": "416-111-1111",
"capacity": 10
}However, the following examples of request body are not valid, and you'll be getting an error with status code 422 and their corresponding error messages.
{
"city": "Toooooooooooronto",
"phoneNum": "416-111-1111",
"capacity": 10
}{
"city": "Toronto",
"phoneNum": "4161111111",
"capacity": 10
}{
"city": "Toronto",
"phoneNum": "416-111-1111",
"capacity": 10000
}{
"city": "Toronto",
"phoneNum": "999-111-1111",
"capacity": 10
}According to the logic set in
src/interceptors/validate-phone-num.interceptor.ts, if city name is Toronto,
the area code for the phone number should begin with 416 or 647.
Run npm test from the root folder.
See all contributors.
MIT
-@2x.png)