Tao, naturally also. Nature is Tao. Nature, self, self. And so, and so, and so.

preface

Everything in the world is unpredictable. With the rapid development of modern society, the topic of “efficiency” has always been around us. The Internet has improved the operation efficiency of traditional industries, and various frameworks/tools in the development industry have improved the development efficiency of programmers. If you’re a front-end, and you have a need to develop forms; If you are a Node.js backend and you need to do some parameter validation. Then the Dvalidator might be worth a try.

Introduction to the

Dvalidator is an object validation tool that can be used in any JS runtime environment. It is recommended to use the decorator syntax for validation rules. The decorator proposal is currently in Stage2(Draft) and is a preliminary standard, which means it may have some changes. However, decorators are so popular these days that I think it’s ok to use them without worry.

You may be wondering, “Why write a Dvalidator when there are so many tools out there?” . I used the validations that come with Angular.js a few years ago, as well as the validations in Element-UI. Yes, all very well done, these authors are probably a few Mount Qomolangma above me. But I think they are not simple enough (features too strong), not independent (integration of specific framework), I want to do a pure JS object verification, but also very simple, very easy to use. I probably haven’t considered enough applications, but I think I can cover most of them. The user of the Dvalidator just needs to make the rules, initiate the validation, and that’s it. Right! There are only two apis.

Maybe I just want to make a very simple wheel.

Dvalidator

Dvalidator is a clean, extensible, and very useful validation tool based on promises and decorators.

It has the following features:

  • Compatibility: Support for both the latest and older versions of the Decorator
  • Asynchronous: Supports passing Asynchronous functions
  • Ordered: checks according to the order you define
  • Small: Small, source code no more than 200 lines
  • Easy: Simple to use, with only two apis

start

npm install dvalidator --save
Copy the code
npm install @babel/plugin-proposal-decorators --save-dev
Copy the code

Configure the Babel. Config. Js

plugins: [
  [
    '@babel/plugin-proposal-decorators',
    {
      Dvalidator supports the latest Decorator proposal (Legacy: false)
      // The old (Legacy: true) version is also supported, and the Decorator can act on literal objects
      // The latest proposal is recommended according to your preferences}]].Copy the code

use

Assuming we have a requirement that we will validate a User object, the nickname and phone number are required, and the phone number needs to initiate a server remote verification.

Using a Dvalidator, we can write:

// common.js
// We can encapsulate the validation rules and write them in a separate file, so that the business code will be very concise.
import dvalidator from 'dvalidator';

const requiredRule = {
  validator: val= >val ! =null&& val ! = =' '.message: 'required'
};
const required = dvalidator(requiredRule);
const checkPhone = dvalidator(value= > fetch(`xxx/${value}`));

// user-signup.js
// Business logic
class User {
  @required('nickname is required')
  nickname = ' ';
  @checkPhone('phone valid fail')
  @required
  phone = ' ';
}
const user = new User();

user
  .$validate()
  .then(/* success */)
  .catch(({ errors, fields }) = > {
    /* fail */
    alert(errors[0].message);
    // Errors contains error information for each attribute. The structure is consistent, and nested objects are flattened
    // Fields gets the error information in the form of an object and is used to display the error information for each column in the form
  });
Copy the code

You can also practice jsfiddle.net/zeusgo/oy1x…

Api

dvalidator(rule: string | Function | Rule): Dvalidator

A class currie function that you can call an infinite number of times to enrich or override rules.

You need to pass in a rule, which can be a function (validation method), a string (error message), or an object (a collection of both).

Such as:

dvalidator({
  validator: val= > {
    // Your validation part of the code
    // Can return Boolean (synchronous) or Promise (asynchronous)
  },
  // Check error will return to you
  message: ' '
});
Copy the code

A validation rule wants to return different error messages:

// Pass different messages
dvalidator(checkPhone)('msg1');
dvalidator(checkPhone)('msg2');
Copy the code
// Error messages can also be returned dynamically
dvalidator((a)= > {
  return Promise.reject(x ? 'msg1' : 'msg2');
});
Copy the code

$validate(filter? : Function): Promise<ValidateError | void>

When you add a decorator to an object, it becomes a “verifiable object” and you can use this method to verify data. Filter is a method for filtering properties. We can use it to do some dynamic validation.

/ / return Promise
user
  .$validate(fieldKey= > {
    // Here you can define your filtering logic
    // If the object is nested, then the fieldKey will be concatenated
    // For example, user: {like: {game: 'lol'}}
    return /^like\.game/.test(fieldKey);
  })
  .catch(({ errors, fields }) = > {
    // xxx
  });
Copy the code

Interface declaration file

See more detailed structure information here! index.d.ts

And More

Enjoy it!