Async-validator is a pure JS library that performs asynchronous validation of data. The async-validator is modified based on the early async-validate. However, the early async-validate has not been used by more people. Instead, the modified async-validator has attracted many people’s attention and use. At present, the star number is around 5.2K, which is quite easy to use for form verification. Always curious about how Form validation is done in Ant. Design. Then holding the attitude of learning to github to find the next, and then found it, this author is also excellent.

Ant. Design forms use rC-Forms to encapsulate form components, and rC-Forms use async-Validator to validate forms. Element – UI also uses async-Validator for form validation.

import schema from 'async-validator';

let descriptor = {
    name: {
        type: "string".required: true.validator: (rule, value) = > value === 'muji',},age: {
        type: "number".asyncValidator: (rule, value) = > {
            return new Promise((resolve, reject) = > {
                if (value < 18) {
                    reject("too young");  // reject with error message
                } else{ resolve(); }}); }},address: {
        validator(rule, value, callback){
            return value === 'test';
        },
        message: 'Value is not equal to "test".',}};let validator = new schema(descriptor);
validator.validate({name: "muji"}, (errors, fields) => {
    if(errors) {
        // validation failed, errors is an array of all errors
        // fields is an object keyed by field name with an array of
        // errors per field
        return handleErrors(errors, fields);
    }
    // validation passed
});

// PROMISE USAGE
validator.validate({ name: "muji".age: 16 }).then((a)= > {
    // validation passed or without error message
}).catch(({ errors, fields }) = > {
    return handleErrors(errors, fields);
})
Copy the code
  • mandatoryrequired

Indicates whether the field is mandatory

  • The blank spacewhitespace

Indicates whether multiple (or more than one) consecutive Spaces are allowed to precede an input string

  • Type the type

    Represents the type of value that the field is allowed to receive

    • integer– plastic
    • float– floating-point
    • array– an array
    • regexp— Regular expressions
    • objectObject –
    • methodThe function, function
    • email– email
    • number– digital
    • date— Date new Date()
    • url– the url
    • hex— Hexadecimal number
  • The interval range

    Represents the length of the value accepted by the field, the minimum and maximum range of values allowed

    • length— Fixed length
    • min– the minimum
    • maxA maximum –
    • range— [minimum, maximum]
  • Enumeration enum

Enumeration allows the value of the field to conform to at least one of them

  • regularpattern

The regular expression is used to match the received value of the field