async-validator README.rd 翻译

async-validator


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

这是一个异步表单验证插件,参考于: https://github.com/freeformsystems/async-validate

NPM version build status Test coverage gemnasium deps node version npm download

API

The following is modified from earlier version of async-validate.

以下内容来自于早期版本。

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:

基本用法包括定义descriptor,把它分给schema,并将要验证的对象和回调函数传递给模式的validate方法:

var schema = require('async-validator');
var descriptor = {
  name: {type: "string", required: true}
}
var 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
});

Validate

function(source, [options], callback)
  • 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 (required). 回调函数(必须)

Options

  • 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.

  • first: Boolean,当第一个验证规则出错时调用回调函数,不再处理其他验证规则。如果验证涉及到多个异步调用(比如数据库查询),我们只需要第一次错误的时候使用这个选项。

  • 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.

  • firstFields: Boolean|String[] 当指定字段的第一个验证规则出错时调用回调函数,不再处理统一字段的验证规则。 true表示所有字段。

Rules

Rules may be functions that perform validation.

Rules可以是执行验证的函数。

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.
  • 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 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 messagesexception and error.

传递给validate的选项将传递给验证函数,以便您可以在验证函数中引用瞬态数据(例如模型引用)。 但是,保留了一些选项名称; 如果使用选项对象的这些属性,则会覆盖它们。 保留的属性是消息,异常和错误。

var schema = require('async-validator');
var descriptor = {
  name(rule, value, callback, source, options) {
    var errors = [];
    if(!/^[a-z0-9]+$/.test(value)) {
      errors.push(
        new Error(
          util.format("%s must be lowercase alphanumeric characters",
            rule.field)));
    }
    callback(errors);
  }
}
var 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:

对于单个字段来说,通常需要多个验证规则,这些规则以数组展示,例如:

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

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

Type类型如下:

  • string: Must be of type stringThis 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.
Required

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

required 表明字段必须是被验证的对象的。

Pattern

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

pattern说明使用正则表达式,该表达式必须匹配才能通过验证。

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.

range是使用min和max属性定义的。string和array,对length进行比较。number类型则是值在min和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.

要验证字段的确切长度,请指定len属性。对于string和array类型比较是在length属性上执行的,对于number类型来说,这个属性表示一个精确匹配的数字,也就是说,它可能只与len严格相等。
如果len属性与min和max range属性相结合,len优先。

Enumerable

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:

为了从一个列表中验证一个值,使用enum类型的enum属性列出该字段的有效值,例如:

var 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.

只包含空格要报错的。要为只包含空白的字符串添加额外的测试,将空白属性添加到具有true值的规则中。规则必须是string类型。
您可能希望对用户输入进行过滤,而不是对空白进行测试,请参阅transform,以获得允许您删除空白的示例。

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.

如果你需要验证多层对象属性,可以通过将嵌套规则分配给规则的字段属性来验证string或array类型。

var 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}
}
var validator = new schema(descriptor);
validator.validate({ address: {} }, (errors, fields) => {
  // errors for street, address.city, address.zip and address.name
});

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.

请注意,如果没有在父规则上指定所需的属性,那么对于不在源对象上声明的字段是完全有效的,并且深度验证规则将不会被执行,因为没有什么可以验证的。
深度规则验证为嵌套规则创建了一个模式,因此您还可以指定传递给schema.validate()方法的选项。

var descriptor = {
  address: {
    type: "object", required: true, options: {single: true, 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}
}
var validator = new schema(descriptor);
validator.validate({ address: {} }, (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:

父规则也经过验证,因此如果您有一组规则,例如:

var 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.

并提供{roles:[“admin”,“user”]}的源对象,然后会有两个错误。 一个用于数组长度不匹配,另一个用于索引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:

defaultField属性可与数组或对象类型一起使用,以验证容器的所有值。 它可以是包含验证规则的对象或数组。 例如:

var descriptor = {
  urls: {
    type: "array", required: true,
    defaultField: {type: "url"}
  }
}

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

请注意,defaultField扩展于field,请参阅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 re-assigned to the source object to mutate the value of the property in place.

有时需要在验证之前转换值,可能是为了强制价值或以某种方式对其进行消毒。 为此,请将验证规则添加到转换函数中。 在验证之前转换该属性,并将其重新分配给源对象,以便在适当的位置改变属性的值。

var schema = require('async-validator');
var sanitize = require('validator').sanitize;
var descriptor = {
  name: {
    type: "string",
    required: true, pattern: /^[a-z]+$/,
    transform(value) {
      return sanitize(value).trim();
    }
  }
}
var validator = new schema(descriptor);
var source = {name: " user  "};
validator.validate(source, (errors, fields) => {
  assert.equal(source.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.

如果没有transform函数,由于模式不匹配,验证将失败,因为输入包含前导空格和尾随空格,但通过添加转换函数验证通道并同时清理字段值。

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>}}

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:

根据您的应用程序要求,您可能需要i18n支持,或者您可能更喜欢不同的验证错误消息。

实现这个的最简单方法是为规则分配message:
{name:{type:“string”,required:true,message:“Name is required”}}
消息可以是任何类型,例如jsx格式。
{name:{type:“string”,required:true,message:<b>姓名是必需的</ b>}}
您可能需要针对不同语言使用相同的架构验证规则,在这种情况下,复制每种语言的架构规则是没有意义的。
在这种情况下,您只需提供自己的语言消息并将其分配给架构:

var schema = require('async-validator');
var cn = {
  required: '%s 必填',
};
var descriptor = {name:{type: "string", required: true}};
var 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.

如果要定义自己的验证函数,最好将消息字符串分配给消息对象,然后通过验证函数中的options.messages属性访问消息。

validator

you can custom validate function for specified field:

您可以自定义验证指定字段的功能:

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

Test Case

npm test
npm run chrome-test

Coverage

npm run coverage

open coverage/ dir

License

Everything is MIT.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值