填写这份《一分钟调查》,帮我们(开发组)做得更好!去填写Home

Validators

提供一组内置验证器,可用于各种表单控件。

Provides a set of built-in validators that can be used by form controls.

查看"说明"...

      
      class Validators {
  static min(min: number): ValidatorFn
  static max(max: number): ValidatorFn
  static required(control: AbstractControl): ValidationErrors | null
  static requiredTrue(control: AbstractControl): ValidationErrors | null
  static email(control: AbstractControl): ValidationErrors | null
  static minLength(minLength: number): ValidatorFn
  static maxLength(maxLength: number): ValidatorFn
  static pattern(pattern: string | RegExp): ValidatorFn
  static nullValidator(control: AbstractControl): ValidationErrors | null
  static compose(validators: ValidatorFn[]): ValidatorFn | null
  static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null
}
    

参见

说明

验证器就是一个函数,它可以处理单个 FormControl 或一组控件,并返回一个错误映射表(map)或 null。null 表示验证已通过了。

A validator is a function that processes a FormControl or collection of controls and returns an error map or null. A null map means that validation has passed.

静态方法

此验证器要求控件的值大于或等于指定的数字。 它只有函数形式,没有指令形式。

Validator that requires the control's value to be greater than or equal to the provided number.

See also:

  • updateValueAndValidity()

      
      static min(min: number): ValidatorFn
    
参数
min number
返回值

如果验证失败,则此验证器函数返回一个带有 min 属性的映射表(map),否则为 null

ValidatorFn: A validator function that returns an error map with the min property if the validation check fails, otherwise null.

使用说明

验证至少为 3
Validate against a minimum of 3
      
      const control = new FormControl(2, Validators.min(3));

console.log(control.errors); // {min: {min: 3, actual: 2}}
    

此验证器要求控件的值小于等于指定的数字。 它只有函数形式,没有指令形式。

Validator that requires the control's value to be less than or equal to the provided number.

See also:

  • updateValueAndValidity()

      
      static max(max: number): ValidatorFn
    
参数
max number
返回值

如果验证失败,则此验证器函数返回一个带有 max 属性的映射表(map),否则为 null

ValidatorFn: A validator function that returns an error map with the max property if the validation check fails, otherwise null.

使用说明

验证最大为 15
Validate against a maximum of 15
      
      const control = new FormControl(16, Validators.max(15));

console.log(control.errors); // {max: {max: 15, actual: 16}}
    

此验证器要求控件具有非空值。

Validator that requires the control have a non-empty value.

See also:

  • updateValueAndValidity()

      
      static required(control: AbstractControl): ValidationErrors | null
    
参数
control AbstractControl
返回值

如果验证失败,则此验证器函数返回一个带有 required 属性的映射表(map),否则为 null

ValidationErrors | null: An error map with the required property if the validation check fails, otherwise null.

使用说明

验证该字段不是空的
Validate that the field is non-empty
      
      const control = new FormControl('', Validators.required);

console.log(control.errors); // {required: true}
    

此验证器要求控件的值为真。它通常用来验证检查框。

Validator that requires the control's value be true. This validator is commonly used for required checkboxes.

See also:

  • updateValueAndValidity()

      
      static requiredTrue(control: AbstractControl): ValidationErrors | null
    
参数
control AbstractControl
返回值

如果验证失败,则此验证器函数返回一个带有 required 属性、值为 true 的映射表(map),否则为 null

ValidationErrors | null: An error map that contains the required property set to true if the validation check fails, otherwise null.

使用说明

验证字段值为真
Validate that the field value is true
      
      const control = new FormControl('', Validators.requiredTrue);

console.log(control.errors); // {required: true}
    

此验证器要求控件的值能通过 email 格式验证。

Validator that requires the control's value pass an email validation test.

See also:

  • updateValueAndValidity()

      
      static email(control: AbstractControl): ValidationErrors | null
    
参数
control AbstractControl
返回值

如果验证失败,则此验证器函数返回一个带有 email 属性的映射表(map),否则为 null

ValidationErrors | null: An error map with the email property if the validation check fails, otherwise null.

使用适合普通用例的正则表达式模式测试值。该模式基于 WHATWG HTML 规范中有效电子邮件地址的定义,并进行了一些增强以支持更多的 RFC 规则(例如与域名相关的规则以及地址不同部分的长度)。

Tests the value using a regular expression pattern suitable for common usecases. The pattern is based on the definition of a valid email address in the WHATWG HTML specification with some enhancements to incorporate more RFC rules (such as rules related to domain names and the lengths of different parts of the address).

与 WHATWG 版本的区别包括:

The differences from the WHATWG version include:

  • 禁止 local-part@ 符号前面的部分)以句点( . )开头或结尾。

    Disallow local-part (the part before the @ symbol) to begin or end with a period (.).

  • 不允许 local-part 超过 64 个字符。

    Disallow local-part to be longer than 64 characters.

  • 不允许整个地址超过 254 个字符。

    Disallow the whole address to be longer than 254 characters.

如果此模式不能满足你的业务需求,则可以使用 Validators.pattern() 来针对其他模式验证值。

If this pattern does not satisfy your business needs, you can use Validators.pattern() to validate the value against a different pattern.

使用说明

验证该字段匹配有效的 email 格式。
Validate that the field matches a valid email pattern
      
      const control = new FormControl('bad@', Validators.email);

console.log(control.errors); // {email: true}
    

此验证器要求控件值的长度大于等于所指定的最小长度。当使用 HTML5 的 minlength 属性时,此验证器也会生效。

Validator that requires the length of the control's value to be greater than or equal to the provided minimum length. This validator is also provided by default if you use the the HTML5 minlength attribute. Note that the minLength validator is intended to be used only for types that have a numeric length property, such as strings or arrays. The minLength validator logic is also not invoked for values when their length property is 0 (for example in case of an empty string or an empty array), to support optional controls. You can use the standard required validator if empty values should not be considered valid.

See also:

  • updateValueAndValidity()

      
      static minLength(minLength: number): ValidatorFn
    
参数
minLength number
返回值

如果验证失败,则此验证器函数返回一个带有 minlength 属性的映射表(map),否则为 null

ValidatorFn: A validator function that returns an error map with the minlength property if the validation check fails, otherwise null.

使用说明

验证该字段至少有 3 个字符
Validate that the field has a minimum of 3 characters
      
      const control = new FormControl('ng', Validators.minLength(3));

console.log(control.errors); // {minlength: {requiredLength: 3, actualLength: 2}}
    
      
      <input minlength="5">
    

此验证器要求控件值的长度小于等于所指定的最大长度。当使用 HTML5 的 maxlength 属性时,此验证器也会生效。

Validator that requires the length of the control's value to be less than or equal to the provided maximum length. This validator is also provided by default if you use the the HTML5 maxlength attribute. Note that the maxLength validator is intended to be used only for types that have a numeric length property, such as strings or arrays.

See also:

  • updateValueAndValidity()

      
      static maxLength(maxLength: number): ValidatorFn
    
参数
maxLength number
返回值

如果验证失败,则此验证器函数返回一个带有 maxlength 属性的映射表(map),否则为 null

ValidatorFn: A validator function that returns an error map with the maxlength property if the validation check fails, otherwise null.

使用说明

验证该字段最多具有 5 个字符
Validate that the field has maximum of 5 characters
      
      const control = new FormControl('Angular', Validators.maxLength(5));

console.log(control.errors); // {maxlength: {requiredLength: 5, actualLength: 7}}
    
      
      <input maxlength="5">
    

此验证器要求控件的值匹配某个正则表达式。当使用 HTML5 的 pattern 属性时,它也会生效。

Validator that requires the control's value to match a regex pattern. This validator is also provided by default if you use the HTML5 pattern attribute.

See also:

  • updateValueAndValidity()

      
      static pattern(pattern: string | RegExp): ValidatorFn
    
参数
pattern string | RegExp

用于测试值的正则表达式或字符串。如果传递了字符串,会在它前面追加 ^ 字符,并在后面追加 $ 字符(如果尚不存在),然后使用所得的正则表达式测试这些值。

A regular expression to be used as is to test the values, or a string. If a string is passed, the ^ character is prepended and the $ character is appended to the provided string (if not already present), and the resulting regular expression is used to test the values.

返回值

如果验证失败,则此验证器函数返回一个带有 pattern 属性的映射表(map),否则为 null

ValidatorFn: A validator function that returns an error map with the pattern property if the validation check fails, otherwise null.

使用说明

验证该字段只包含字母或空格
Validate that the field only contains letters or spaces
      
      const control = new FormControl('1', Validators.pattern('[a-zA-Z ]*'));

console.log(control.errors); // {pattern: {requiredPattern: '^[a-zA-Z ]*$', actualValue: '1'}}
    
      
      <input pattern="[a-zA-Z ]*">
    
带有全局或粘性(sticky)标志的匹配模式
Pattern matching with the global or sticky flag

当要连续运行验证时,使用传递给 Validators.patterngy 标志创建的 RegExp 对象可以在同一输入上产生不同的结果。这是由于在 ECMA-262 中RegExp.prototype.test 定义的行为(RegExp 保留了最后一个匹配项的索引)。由于这种现象,建议你使用 Validators.pattern不要传入启用了全局或粘性标志的 RegExp

RegExp objects created with the g or y flags that are passed into Validators.pattern can produce different results on the same input when validations are run consecutively. This is due to how the behavior of RegExp.prototype.test is specified in ECMA-262 (RegExp preserves the index of the last match when the global or sticky flag is used). Due to this behavior, it is recommended that when using Validators.pattern you do not pass in a RegExp object with either the global or sticky flag enabled.

      
      // Not recommended (since the `g` flag is used)
const controlOne = new FormControl('1', Validators.pattern(/foo/g));

// Good
const controlTwo = new FormControl('1', Validators.pattern(/foo/));
    

此验证器什么也不做。

Validator that performs no operation.

See also:

  • updateValueAndValidity()

      
      static nullValidator(control: AbstractControl): ValidationErrors | null
    
参数
control AbstractControl
返回值

ValidationErrors | null

把多个验证器合并成一个函数,它会返回指定控件的各个错误映射表的并集。

Compose multiple validators into a single function that returns the union of the individual error maps for the provided control.

      
      static compose(validators: null): null
    
参数
validators null
返回值

如果验证失败,则此验证器函数返回各个验证器所返回错误对象的一个并集,否则为 null

null: A validator function that returns an error map with the merged error maps of the validators if the validation check fails, otherwise null.

      
      static compose(validators: ValidatorFn[]): ValidatorFn | null
    
参数
validators ValidatorFn[]
返回值

ValidatorFn | null

把多个异步验证器合并成一个函数,它会返回指定控件的各个错误映射表的并集。

Compose multiple async validators into a single function that returns the union of the individual error objects for the provided control.

See also:

  • updateValueAndValidity()

      
      static composeAsync(validators: AsyncValidatorFn[]): AsyncValidatorFn | null
    
参数
validators AsyncValidatorFn[]
返回值

如果验证失败,则此验证器函数返回各异步验证器所返回错误对象的一个并集,否则为 null

AsyncValidatorFn | null: A validator function that returns an error map with the merged error objects of the async validators if the validation check fails, otherwise null.