Why?

In the development, often encounter data verification, need a simple, accurate elegant calibration database for some data verification.

The scenario is as follows:

  • Verifying configuration files
  • Data verification for docking with others
  • Verification of interface parameters
  • and so on…

The community looked for it, but it didn’t seem to be what I wanted, so I just wrote one by myself and rolled up my sleeves to do it.

This article mainly explains how to use, and the implementation principle.

API preview

const Struct = require("@axetroy/struct");

const data = {
  name: "axetroy".age: 18
};

const struct = truct({
  name: Struct.type.string,
  age: Struct.type.int
});

const err = struct.validate(data);

console.log(err); // undefined, because the data pass the validatorCopy the code

Realize the principle of

  1. Construct a Struct object, passing in the types of each field
  2. Type definition usesStruct.type.xxx
  3. callstruct.validate(data)check

Resolution:

Struct.type returns new type (), and on the prototype of the type object, a set of built-in methods are defined.

Struct.type.string = new type ().string;} struct.type.string = new type ().string;

Struct.validate (data); struct.validate(data); struct.validate(data); struct.validate(data);

Supported Types

Built-in support for int, float, string, and so on. As well as support for nested object verification, support array verification.

Not built in enough? So let’s go from the definition

Call struct.define (name, func) to add the corresponding method on type.prototype.

For example, struct.define (“email”, func), you can add a validator struct.type.email

One field can have multiple validators (chained call)

Here’s the full example:

const Struct = require(".. /index");

Struct.define("email".function(input) {
  return /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.) Tobacco on {1} [a - z0-9] + $/.test(
    input
  );
});

const data = {
  name: "axetroy".age: 18.email: "[email protected]"
};

const struct = truct({
  name: Struct.type.string,
  age: Struct.type.int,
  email: Struct.type.string.email // check string first, and then check email
});

const err = struct.validate(data);

console.log(err); // undefined, because the data pass the validatorCopy the code

You can even define a type check with parameters. Here’s a demo

The last

The code has been tested, coverage is close to 100%, safe to eat

By the way, why is the test for the object.hasOwnProperty(key) branch always not covered

Welcome to do, issue or PR

Github.com/axetroy/str…

Axetroy. xyz/#/post/136