In some Web applications, forms are more difficult to process than other functional modules. A lot of manual work, often in the data validation can be very time-consuming, since I used schema-typed (github.com/rsuite/sche… The tool found that many scenarios became surprisingly simple.

The installation

npm install schema-typed --save
Copy the code

The sample

import { SchemaModel, StringType, DateType, NumberType, ObjectType, ArrayType } from 'schema-typed';
const model = SchemaModel({
  username: StringType().isRequired('Username required'),
  email: StringType().isEmail('Email required'),
  age: NumberType('Age should be a number').range(18.30.'Over the age limit'),
  tags: ArrayType().of(StringType('The tag should be a string').isRequired()),
  role: ObjectType.shape({
    name: StringType().isRequired('Name required'),
    permissions: ArrayType().isRequired('Permissions required')})});const checkResult = model.check({
  username: 'foobar'.email: '[email protected]'.age: 40.tags: ['Sports'.'Games'.10].role: { name: 'administrator'}});console.log(checkResult);
Copy the code

The return structure of the sample code is as follows:

{
  username: { hasError: false },
  email: { hasError: false },
  age: { hasError: true.errorMessage: 'Over the age limit' },
  tags: {
    hasError: true.array: [{hasError: false },
      { hasError: false },
      { hasError: true.errorMessage: 'The tag should be a string'}},role: {
    hasError: true.object: {
      name: { hasError: false },
      permissions: { hasError: true.errorMessage: 'Permissions required'}}}};Copy the code

Data multiple validation

StringType()
  .minLength(6."Can't be less than 6 characters")
  .maxLength(30.'Cannot be greater than 30 characters')
  .isRequired('This field required');
Copy the code

Data custom validation

We can customize some rules by using an addRule function; You can also set up a regular expression through the Pattern method for custom validation

const model = SchemaModel({
  field1: StringType().addRule((value, data) = > {
    return /^[1-9][0-9]{3}\s? [a-zA-Z]{2}$/.test(value);
  }, 'Please enter legal characters'),
  field2: StringType().pattern(/^[1-9][0-9]{3}\s? [a-zA-Z]{2}$/.'Please enter legal characters')}); model.check({field1: ' '.field2: ' ' });

/** { field1: { hasError: true, errorMessage: 'Please enter legal characters' }, field2: { hasError: true, errorMessage: 'Please enter legal characters' } }; * * /
Copy the code

Data multi-field interactive validation

The following example is used to verify that two passwords are the same

const model = SchemaModel({
  password1: StringType().isRequired('This field required'),
  password2: StringType().addRule((value, data) = > {
    if(value ! == data.password1) {return false;
    }
    return true;
  }, 'The passwords are inconsistent twice')}); model.check({password1: '123456'.password2: 'root' });

/** { password1: { hasError: false }, password2: { hasError: true, errorMessage: 'The passwords are inconsistent twice' } } **/
Copy the code

Asynchronous check

The following example is used to verify whether the mailbox is duplicated

function asyncCheckEmail(email) {
  return new Promise(resolve= > {
    setTimeout(() = > {
      if (email === '[email protected]') {
        resolve(false);
      } else {
        resolve(true); }},500);
  });
}

const model = SchemaModel({
  email: StringType()
    .isEmail('Please input the correct email address')
    .addRule((value, data) = > {
      return asyncCheckEmail(value);
    }, 'Email address already exists')
    .isRequired('This field cannot be empty')}); model.checkAsync({email: '[email protected]' }).then(checkResult= > {
  console.log(checkResult);
  /** { email: { hasError: true, errorMessage: 'Email address already exists' } }; * * /
});
Copy the code

Validate nested objects

Validates nested objects that can be defined using the ObjectType() method. Such as:

const model = SchemaModel({
  id: NumberType().isRequired('This field required'),
  name: StringType().isRequired('This field required'),
  info: ObjectType().shape({
    email: StringType().isEmail('Should be an email'),
    age: NumberType().min(18.'Age should be greater than 18 years old')})});const user = {
  id: 1.name: ' '.info: { email: 'schema-type'.age: 17}}; model.check(data);/** { "id": { "hasError": false }, "name": { "hasError": true, "errorMessage": "This field required" }, "info": { "hasError": true, "object": { "email": { "hasError": true, "errorMessage": "Should be an email" }, "age": { "hasError": true, "errorMessage": "Age should be greater than 18 years old" } } } } */
Copy the code

Combination check

SchemaModel provides a static method composition that can be combined with multiple SchemaModel to return a new SchemaModel.

const model1 = SchemaModel({
  username: StringType().isRequired('This field required'),
  email: StringType().isEmail('Should be an email')});const model2 = SchemaModel({
  username: StringType().minLength(7."Can't be less than 7 characters"),
  age: NumberType().range(18.30.'Age should be greater than 18 years old')});const model3 = SchemaModel({
  groupId: NumberType().isRequired('This field required')});const model4 = SchemaModel.combine(model1, model2, model3);

model4.check({
  username: 'foobar'.email: '[email protected]'.age: 40.groupId: 1
});
Copy the code

The commonly used API

For details, please refer to github.com/rsuite/sche…

  • SchemaModel
  • StringType
  • NumberType
  • ArrayType
  • DateType
  • ObjectType
  • BooleanType