Coder Social home page Coder Social logo

async-validator's Introduction

async-validator

NPM version build status Test coverage node version npm download npm bundle size (minified + gzip)

Validate form asynchronous. A variation of https://github.com/freeformsystems/async-validate

Install

npm i async-validator

Usage

Basic usage involves defining a descriptor, assigning it to a schema and passing the object to be validated and a callback function to the validate method of the schema:

import Schema from 'async-validator';
const 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();
        }
      });
    },
  },
};
const 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(() => {
  // validation passed or without error message
}).catch(({ errors, fields }) => {
  return handleErrors(errors, fields);
});

API

Validate

function(source, [options], callback): Promise
  • source: The object to validate (required).
  • options: An object describing processing options for the validation (optional).
  • callback: A callback function to invoke when validation completes (optional).

The method will return a Promise object like:

  • then(),validation passed
  • catch({ errors, fields }),validation failed, errors is an array of all errors, fields is an object keyed by field name with an array of errors per field

Options

  • suppressWarning: Boolean, whether to suppress internal warning about invalid value.

  • first: Boolean, Invoke callback when the first validation rule generates an error, no more validation rules are processed. If your validation involves multiple asynchronous calls (for example, database queries) and you only need the first error use this option.

  • firstFields: Boolean|String[], Invoke callback when the first validation rule of the specified field generates an error, no more validation rules of the same field are processed. true means all fields.

Rules

Rules may be functions that perform validation.

function(rule, value, callback, source, options)
  • rule: The validation rule in the source descriptor that corresponds to the field name being validated. It is always assigned a field property with the name of the field being validated.
  • value: The value of the source object property being validated.
  • callback: A callback function to invoke once validation is complete. It expects to be passed an array of Error instances to indicate validation failure. If the check is synchronous, you can directly return a false or Error or Error Array.
  • source: The source object that was passed to the validate method.
  • options: Additional options.
  • options.messages: The object containing validation error messages, will be deep merged with defaultMessages.

The options passed to validate or asyncValidate are passed on to the validation functions so that you may reference transient data (such as model references) in validation functions. However, some option names are reserved; if you use these properties of the options object they are overwritten. The reserved properties are messages, exception and error.

import Schema from 'async-validator';
const descriptor = {
  name(rule, value, callback, source, options) {
    const errors = [];
    if (!/^[a-z0-9]+$/.test(value)) {
      errors.push(new Error(
        util.format('%s must be lowercase alphanumeric characters', rule.field),
      ));
    }
    return errors;
  },
};
const validator = new Schema(descriptor);
validator.validate({ name: 'Firstname' }, (errors, fields) => {
  if (errors) {
    return handleErrors(errors, fields);
  }
  // validation passed
});

It is often useful to test against multiple validation rules for a single field, to do so make the rule an array of objects, for example:

const descriptor = {
  email: [
    { type: 'string', required: true, pattern: Schema.pattern.email },
    { 
      validator(rule, value, callback, source, options) {
        const errors = [];
        // test if email address already exists in a database
        // and add a validation error to the errors array if it does
        return errors;
      },
    },
  ],
};

Type

Indicates the type of validator to use. Recognised type values are:

  • string: Must be of type string. This is the default type.
  • number: Must be of type number.
  • boolean: Must be of type boolean.
  • method: Must be of type function.
  • regexp: Must be an instance of RegExp or a string that does not generate an exception when creating a new RegExp.
  • integer: Must be of type number and an integer.
  • float: Must be of type number and a floating point number.
  • array: Must be an array as determined by Array.isArray.
  • object: Must be of type object and not Array.isArray.
  • enum: Value must exist in the enum.
  • date: Value must be valid as determined by Date
  • url: Must be of type url.
  • hex: Must be of type hex.
  • email: Must be of type email.
  • any: Can be any type.

Required

The required rule property indicates that the field must exist on the source object being validated.

Pattern

The pattern rule property indicates a regular expression that the value must match to pass validation.

Range

A range is defined using the min and max properties. For string and array types comparison is performed against the length, for number types the number must not be less than min nor greater than max.

Length

To validate an exact length of a field specify the len property. For string and array types comparison is performed on the length property, for the number type this property indicates an exact match for the number, ie, it may only be strictly equal to len.

If the len property is combined with the min and max range properties, len takes precedence.

Enumerable

Since version 3.0.0 if you want to validate the values 0 or false inside enum types, you have to include them explicitly.

To validate a value from a list of possible values use the enum type with a enum property listing the valid values for the field, for example:

const descriptor = {
  role: { type: 'enum', enum: ['admin', 'user', 'guest'] },
};

Whitespace

It is typical to treat required fields that only contain whitespace as errors. To add an additional test for a string that consists solely of whitespace add a whitespace property to a rule with a value of true. The rule must be a string type.

You may wish to sanitize user input instead of testing for whitespace, see transform for an example that would allow you to strip whitespace.

Deep Rules

If you need to validate deep object properties you may do so for validation rules that are of the object or array type by assigning nested rules to a fields property of the rule.

const descriptor = {
  address: {
    type: 'object',
    required: true,
    fields: {
      street: { type: 'string', required: true },
      city: { type: 'string', required: true },
      zip: { type: 'string', required: true, len: 8, message: 'invalid zip' },
    },
  },
  name: { type: 'string', required: true },
};
const validator = new Schema(descriptor);
validator.validate({ address: {} }, (errors, fields) => {
  // errors for address.street, address.city, address.zip
});

Note that if you do not specify the required property on the parent rule it is perfectly valid for the field not to be declared on the source object and the deep validation rules will not be executed as there is nothing to validate against.

Deep rule validation creates a schema for the nested rules so you can also specify the options passed to the schema.validate() method.

const descriptor = {
  address: {
    type: 'object',
    required: true,
    options: { first: true },
    fields: {
      street: { type: 'string', required: true },
      city: { type: 'string', required: true },
      zip: { type: 'string', required: true, len: 8, message: 'invalid zip' },
    },
  },
  name: { type: 'string', required: true },
};
const validator = new Schema(descriptor);

validator.validate({ address: {} })
  .catch(({ errors, fields }) => {
    // now only errors for street and name    
  });

The parent rule is also validated so if you have a set of rules such as:

const descriptor = {
  roles: {
    type: 'array',
    required: true,
    len: 3,
    fields: {
      0: { type: 'string', required: true },
      1: { type: 'string', required: true },
      2: { type: 'string', required: true },
    },
  },
};

And supply a source object of { roles: ['admin', 'user'] } then two errors will be created. One for the array length mismatch and one for the missing required array entry at index 2.

defaultField

The defaultField property can be used with the array or object type for validating all values of the container. It may be an object or array containing validation rules. For example:

const descriptor = {
  urls: {
    type: 'array',
    required: true,
    defaultField: { type: 'url' },
  },
};

Note that defaultField is expanded to fields, see deep rules.

Transform

Sometimes it is necessary to transform a value before validation, possibly to coerce the value or to sanitize it in some way. To do this add a transform function to the validation rule. The property is transformed prior to validation and returned as promise result or callback result when pass validation.

import Schema from 'async-validator';
const descriptor = {
  name: {
    type: 'string',
    required: true,
    pattern: /^[a-z]+$/,
    transform(value) {
      return value.trim();
    },
  },
};
const validator = new Schema(descriptor);
const source = { name: ' user  ' };

validator.validate(source)
  .then((data) => assert.equal(data.name, 'user'));

validator.validate(source,(errors, data)=>{
  assert.equal(data.name, 'user'));
});

Without the transform function validation would fail due to the pattern not matching as the input contains leading and trailing whitespace, but by adding the transform function validation passes and the field value is sanitized at the same time.

Messages

Depending upon your application requirements, you may need i18n support or you may prefer different validation error messages.

The easiest way to achieve this is to assign a message to a rule:

{ name: { type: 'string', required: true, message: 'Name is required' } }

Message can be any type, such as jsx format.

{ name: { type: 'string', required: true, message: '<b>Name is required</b>' } }

Message can also be a function, e.g. if you use vue-i18n:

{ name: { type: 'string', required: true, message: () => this.$t( 'name is required' ) } }

Potentially you may require the same schema validation rules for different languages, in which case duplicating the schema rules for each language does not make sense.

In this scenario you could just provide your own messages for the language and assign it to the schema:

import Schema from 'async-validator';
const cn = {
  required: '%s 必填',
};
const descriptor = { name: { type: 'string', required: true } };
const validator = new Schema(descriptor);
// deep merge with defaultMessages
validator.messages(cn);
...

If you are defining your own validation functions it is better practice to assign the message strings to a messages object and then access the messages via the options.messages property within the validation function.

asyncValidator

You can customize the asynchronous validation function for the specified field:

const fields = {
  asyncField: {
    asyncValidator(rule, value, callback) {
      ajax({
        url: 'xx',
        value: value,
      }).then(function(data) {
        callback();
      }, function(error) {
        callback(new Error(error));
      });
    },
  },

  promiseField: {
    asyncValidator(rule, value) {
      return ajax({
        url: 'xx',
        value: value,
      });
    },
  },
};

validator

You can custom validate function for specified field:

const fields = {
  field: {
    validator(rule, value, callback) {
      return value === 'test';
    },
    message: 'Value is not equal to "test".',
  },

  field2: {
    validator(rule, value, callback) {
      return new Error(`${value} is not equal to 'test'.`);
    },
  },
 
  arrField: {
    validator(rule, value) {
      return [
        new Error('Message 1'),
        new Error('Message 2'),
      ];
    },
  },
};

FAQ

How to avoid global warning

import Schema from 'async-validator';
Schema.warning = function(){};

or

globalThis.ASYNC_VALIDATOR_NO_WARNING = 1;

How to check if it is true

Use enum type passing true as option.

{
  type: 'enum',
  enum: [true],
  message: '',
}

Test Case

npm test

Coverage

npm run coverage

Open coverage/ dir

License

Everything is MIT.

async-validator's People

Contributors

dead-horse avatar fanerge avatar fxxjdedd avatar galenjiang avatar geritol avatar iamdhj avatar iamkun avatar janrywang avatar jasonslyvia avatar jpenna avatar junstyle avatar keepfool avatar kouchao avatar lianghx-319 avatar mahovich avatar mov-78 avatar mushan0x0 avatar nicolaichuk avatar noyobo avatar nuintun avatar okxiaoliang4 avatar queimadus avatar spahi4 avatar sunnyshining avatar vv13 avatar ygj6 avatar yiminghe avatar yuchonghua avatar zhouchilly avatar zombiej avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

async-validator's Issues

遍历循环加校验时遇到的问题

需求是统一加上required。但是其中有下拉框(值为number),也有输入框(值为string),此时该怎么定义验证规则呢?尝试的方案有:

  1. { required: true, message: '请输入', trigger: 'blur' },
    { pattern: /^[0-9][1-9][0-9]$/, message: '应为正整数!', trigger: 'blur' }
    结果为xx is not a string
  2. { required: true, message: 'xx是必填项', type : 'regexp' ,trigger: 'blur' },
    { pattern: /^[\s\S]+$/, message: '请输入', trigger: 'blur' }
    结果为 输入为空也通过验证

1.7.1 版本升级 ES6 export

1.7.1 版本升级为 ES6 模块导出,导致依赖模块时,使用 CommonJs 方式导入模块出错,强烈不建议在小版本做这样升级,也希望能够在 Readme 更新使用方式

license in package.json typo

I'm trying to add you're project to webjars but it's being rejected because the license line in package.json is incorrect. It should be "license": "MIT" not "licenses": "MIT".

Very simple fix but then everyone using webjars could use your library.

url 校验类型不支持无协议头 url 的校验

type url 部分的正则自支持校验带协议头的 url,目前集团有相当一批系统产出的 图片 url 等是不附带协议头的 //xxxx 的 url,此时会无法通过校验。

需要修改一下 url 的校验规则,使其支持无协议头的 url。

rule function 里面如何绑定 this,以便能够与外部组件的props比较

        {getFieldDecorator('price', {
            rules: [{
              required: true,
              message: '必填'
            },{
              type: 'number',
              message: '请输入数字'
            },{
              validator(rule, value, callback){
                if(value<20){
                  callback(['出金金额必须大于或等于20'])
                }else if(value < this.props.balance_price){  // 这里
                  callback(['你的余额不足'])
                }
                else{
                  callback([])
                }
              }
            }]
          })(
            <InputNumber/>
          )}

使用r.js打包报错问题

我用r.js打包index文件 生成一个文件压缩js, 在到组件中引用,页面加载了压缩的js但是会出现
Uncaught TypeError: AsyncValidator is not a constructor,在页面中我是这样调用的 var validator = new AsyncValidator(descriptor);

类型为 number 数字验证不通过的BUG

<template>
<el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="提现金额" prop="money">
          <el-input v-model="form.money"></el-input>
        </el-form-item>
      </el-form>
</template>
<script>
export default {
  data() {
    return {
      form:{
        money:null,
      },
      rules: {
        money: [
          { required: true, message: '请输入提现金额', trigger: 'blur' },
          { type:"number", message: '请输入正确的提现金额', trigger: 'blur' }
        ]
      }
    }
  }
</script>

输入数字校验不正确,提示 请输入正确的提现金额

修改源码lib/rule/type.js第56行为

return typeof +value === 'number';

则可以通过验证。

怎么消除初始化时的错误提示?

vm.propertyList.forEach(function(e){
vm.$set(vm.addRule,e.code,[{ required: true, message:'这是必填项', trigger: 'blur', pattern: /^.*$/ }]);
})

如上代码,验证规则是动态遍历添加的,然后在元素加载出来的会出现错误提示,怎么才能取消?急求助啊

表单字段验证不支持多种类型

当表单的字段有多种类型时,抛出错误:

 Error: Unknown rule type object,string

声明的难规则如下:

 rules="{'type':['object', 'string']}"

问题代码:

getType: function getType(rule) {
    if (rule.type === undefined && rule.pattern instanceof RegExp) {
      rule.type = 'pattern';
    }
    if (typeof rule.validator !== 'function' && rule.type && !_validator2["default"].hasOwnProperty(rule.type)) {
      throw new Error((0, _util.format)('Unknown rule type %s', rule.type));
    }
    return rule.type || 'string';
  }

验证国际化的问题

  1. ant design中验证有问题, 比如我对“title”属性验证,国际化消息是“%s不能为空”
    那么验证失败的消息为 "title不能为空";

    我发现可以指定fullField,如果校验规则中配置 fullField:"标题",这样失败消息就是“标题不能为空”

    此时又出现一个bug,第一次校验可用,但是不做任何修改,继续提交再次校验时,antdesign不会对之前校验的再次校验,会把之前的错误拿过来。但是title属性的错误是用fullField标志的,所以拿不到错误。
    就任务校验全部通过了。

可以通过以下方式来解决:
field: oe.field || rule.fullField
改成field: rule.field || rule.fullField

  1. 校验失败时,内置规则智能用内置的提示消息,在规则中提供的校验消息不会被使用
    {
    rule: "required",
    message: "标题千万不能为空"
    }
    这个message不会被使用。

正则校验的问题

{ type: 'regexp', pattern: /^1[0-9]{10}$|^[569][0-9]{7}$/, message: '请填写正确的手机号码' },

校验的写法有问题吗?校验没有任何效果

rules:{required} 对number=0 的检测无效

value=0的时候检测不出来

  it('works for number=0', (done) => {
    new Schema({
      v: {
        required,
      },
    }).validate({
      v: 0,  
    }, (errors) => {
       expect(errors.length).to.be(1);
      expect(errors[0].message).to.be('v is required');
      done();
    });

建议添加动态启用/停用 某一个校验规则的 功能

开发中需要用到一个功能,就是动态的决定是否校验某一个文本框的内容是否合法。
研究了一下其他网友的方案,建议每一个写成自定义规则,但是发现每一个都写成自定义规则感觉有点麻烦,个人觉得可以增加一个类似 toggle 的属性,这个属性接受一个 Boole值或者一个方法 ,用来动态的决定是否 启用这个 校验规则,类似这样:

//接受一个 Boole
toggle:true,


又或者像这样接受一个 function

//接受一个 function
toggle:function(){
   //这里的条件可能是一个非常复杂的逻辑运算结果
    if(this.abc === 123 ){
         return true;
    }else{
        return false;
   }
},

如何更改错误消息的提示位置?

错误信息提示只能显示在输入框的下面吗?有没有控制提示位置参数,或者关掉错误提示通过验证回调函数的方式提示? 感觉文档可以写全点。。。。。

required 优化

在使用校验的时候经常用到

  rules: [{
    // required 也必须配置 type: number =。=
    type: 'number',
    required: true
  }]    

但是这里却要强制指定类型才能完成require校验。后端经常会因为这个小问题来问为什么校验不成功

优化建议:

required:true 的校验中,根据value的类型来判断是

  • value是 null undefined 报错
  • string类型 增加判断 ‘’ 报错
  • array类型 增加空数组报错

建议去除依赖lodash.mergewith

async-validator 用到了 lodash.mergewith, 而 lodash.mergewith又依赖了 lodash._baseclone、lodash._root、lodash.isplainobject、lodash.keysin、lodash.rest

因为mergewith的使用使得整个包的体检增长不少。

next这边正在针对包比较大做排查工作,lodash是其中一部分,而错误校验用到了async-validator,所以希望能够给async-validator瘦身下。

type参数中,类似于email取值,是否可以提供phone或者mobile取值,表示匹配电话号,手机号?

如题

尤其和antd-mobile的表单组件一起使用,手机上输入电话号,手机号的场景还是比较常见的,并且antd-mobile 的InputItem组件是有 type=“phone”的设置,这时候如果能和校验一起使用,那是极好的。省的自己写正则。

ps: antd-mobile 设置type="phone" 的时候,,表单里的取值是 包含空格的,比如 “130 000 0000”,所以校验的时候,容易有问题。不知道是 antd-mobile改进还是在validator这进行适配。? 这个也是我现在遇到的问题之一,我自己在其他地方使用的正则表达式,直接用pattern放到这里,是不能使用,因为前面所说的空格问题。

多谢大神!

add numeric or patch 'number'

export function isNumeric(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Right now it's not possibly to use numbers as strings.

rules {type: 'number', } & <Input type="number"/> bugs

Bad

<Form onSubmit={this.handleSubmit}>
    <FormItem
        {...formItemLayout}
        label="产品编号"
        hasFeedback
        >
        {
            getFieldDecorator('productNum', {
                rules: [
                    {
                        type: 'number', 
                        message: 'The input is not valid 产品编号!'
                    }, 
                    {
                        required: true, 
                        message: 'Please input your 产品编号!'
                    }
                ],
            })(
                <Input type="number"/>
            )
        }
    </FormItem>

OK

<Form onSubmit={this.handleSubmit}>
    <FormItem
        {...formItemLayout}
        label="产品编号"
        hasFeedback
        >
        {
            getFieldDecorator('productNum', {
                rules: [
                    {
                        required: true, 
                        message: 'Please input your 产品编号!'
                    }
                ],
            })(
                <Input type="number"/>
            )
        }
    </FormItem>

Nested validation of all elements of Array

var array = ["google.com", "wrong", "youtube.com"]

There is a way to validate specific fields of an array:

var descriptor = {
  roles: {
    type: "array", required: true,
     fields: {
       0: {type: "url"},
       1: {type: "url"},
       2: {type: "url"}
     }
  }
}

Is there a way to validate all fields of an array?

var descriptor = {
  roles: {
    type: "array", required: true,
    allFields: {type: "url"}
  }
}

File validation ?

Hi, what about file validation ? I mean add type "file" for file validation or add type "image" for image validation. What you think about that ?

校验规则 触发 trigger 可以自定义吗

请问一下你们这个 rule 下面的 触发trigger 可以自定义事件吗 ,我是用的element-ui 的文件上传组件, 想对上传后返回的参数做一个校验。看了你们的源码 貌似没有看到自定义 trigger 的地方。
rules: {
location: [
{ required: true, type:"array", message: '请选择注册所在地', trigger: 'blur' },
{ type:"array", message: '参数类型错误'}
],
checked: [
{ validator: checkbox, message: '请勾选 已阅读《契约锁服务协议》', trigger: 'blur' }
],
uploadFileKey:[
{ required: true, message: "请上传授权委托书" }
]

校验规则中数组配合 defaultField,在被校验的数组为空数组的情况下不会执行回调

[email protected]

示例如下:

    const descriptor = {
      testArray: {
        type: 'array',
        min: 2,
        message: 'test',
        required: true,
        defaultField: {...},
      },
    };
    const record = {
      testArray: [],
    };

    const validator = new Schema(descriptor);
    validator.validate(record, (errors, fields) => {
      console.log(errors, fields);
    });

descriptor 中对数组 testArray 字段配置校验,同时配置 defaultField 规则。
这种情况下,如果被校验的数组为空数组,回调不会被执行。即示例中的 console.log(errors, fields); 不会执行。

Remove field name in custom error messages

I've just followed your example to override default error messages :

var Schema = require('async-validate')
  , messages = require('async-validate/messages')
  , descriptor = {
      type: 'object',
      fields: {
        name:{type: "string", required: true}}
      }
    }
  , schema;
messages.required = "%s is a required field";
schema = new Schema(descriptor, {messages: messages});

In my case, I don't wan't to display field name in error message, so this is what I've done :

messages.required = "This field is required";

But when I'm validating a field (let say "product"), I've got this final error message :

{ 
  "errors": [ {
    "field": "product",
    "key": "product",
    "message": "This field is required product"
  } ]
}

Can't we avoid field name to be concatenated into final error message ?

能否跳过type:string验证

{ required: true }

假如传入的值是number,则报错,称类型不是string。实际上我只希望验证required ,不验证type.

Can you support file type

I use <Input> as file upload component. But in the validator(rule, value, callback), rule.type always be string.

So, can you guys support file type?

数组 defaultField 校验会导致上层校验错误丢失

如下代码:

const Schema = require("async-validator")

const obj = {
    value: '',
    test: [{
        name: 'aa',
    }],
};

const descriptor = {
    test: {
        type: 'array',
        min: 2,
        required: true,
        message: '至少两项',
        defaultField: [{
            type: 'object',
            required: true,
            message: 'test 必须有',
            fields: {
                name: { type: 'string', required: true, message: 'name 必须有' },
            },
        }],
    },
};
const validator = new Schema(descriptor);

validator.validate(obj, (errors, fields) => {
    console.log(errors, fields);
});

运行中会校验出 obj 的 test 数组长度不符合要求,但后续的 defaultField 的校验导致之前的 errors 丢失,最终 log 结果为 null。但,如果 defaultField 的校验没通过,所有的 errors 会正确返回,不会丢失。

在线重现连接:
https://runkit.com/583e9f2905d1c70014aa94da/583e9f2905d1c70014aa94db

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.