We create a validation rule by adding a static method to the model class. The method name is inaudible . The first parameter is the property name. The second parameter is an object that configures the validation rule. To force the minimal length, we set the value of min to three.
Let's try this out. We go to the put products endpoint and pass in our data. When we see the result, we see that we get a validation error. This error message can be enhanced, so let's add a custom message. We can do this by adding a message property, and for the key min, we add a custom message.
When we try again, we see our customer message. Another thing we want to validate is that the name of our product is unique. To do this, we can use the built-in validatesUniquenessOf rule. When we try to resubmit the same product twice, we will see that we get an error message saying name is not unique.
For the price of our product, we want to make sure it's an integer, and the value is zero or higher, Because LoopBack does not have a built-in validator for this, we will write a custom one. First, we will add a regular expression that we can use in our validation method.
Then, we will add a validation method that takes one parameter, which is the error callback. The method uses our regular expression, and triggers the error callback when it does not pass the test. The last thing we want to do is add a validate rule, pass in the property price, add a reference to the validation method, and pass in a friendly error message.
Let's try this out. When we look in the API explorer, we see that we can't any products with a price lower than zero. Great. Another common use case is to use asynchronous validation. For instance, if you want to validate against a value in the database, or if you want to call into an external service, like an API.
We will add a validation method that works asynchronous using process.nextTick. We pretend to get a minimum value of the database and validate this against our price. Once we have our validation method in place, we will add a validate async rule, pass in our property price, add a reference to our validation method, and print a friendly error message.
Let's try this out. When we try to add a price of one, we see that our validation will prevent the product from being added. When we add a price of 100, we see that the product gets persisted.