Joi: A rule description language and validator for javaScript objects

  1. NPM install [email protected]

  2. Create the joi.js file

  3. Import the third-party joI package

const Joi = require(‘joi’);

  1. Custom authentication rules
Const schema = {username: joi.string ().min(2).max(10).required().error(new error(' username does not comply with validation rules ')}Copy the code

5. Use validation rules to verify whether the data matches. Use validate, a joI method, to return a Promise object

Joi.validate({username:'zhangsan'},schema);
Copy the code

6. Because the above method returns a promise, it can be handled with an asynchronous function

Async function run() {try{await joi. validate({username:'zhangsan'},schema); {} the catch (ex). The console log (ex. Message); The return; } console.log(validates '); } the run ();Copy the code

If Joi. Validate is not a function error occurs during rule validation, it may be a version error. Simply uninstall the Joi version and re-install [email protected]

Const Joi = require(' Joi '); // Define the validation rule for the object const schema = {username: Joi.string().min(2).max(10).required().error(new error(' user name does not comply with validation rules '))} async function run() {try {// Validate objects with rules Validate ({username: 'Joi'}, schema); } catch (ex) { console.log(ex.message); return; } console.log(' verified '); } run();Copy the code