【问题标题】:Angular custom validator null plus custom validation checksAngular 自定义验证器 null 加上自定义验证检查
【发布时间】:2018-07-28 15:54:48
【问题描述】:

我想检查空验证和信用卡输入检查。

例如:我有 3 个输入字段名称“卡号”、“到期”、“cvv”。 我想要的是默认情况下它是可选的,但是如果用户在其中一个字段中输入输入,则用户应该在所有 3 个字段中输入有效输入。

所以验证就像所有输入空白或所有输入都必须有值,如果都有值,它应该检查有效的卡输入验证检查(对于卡号和到期检查,我计划用于第 3 方 npm 模块)。

我已经从其他堆栈溢出帖子的参考中这样开始:

this.myForm = new FormGroup({
      'name': new FormControl(),
      'birthYear': new FormControl(),
      'card': new FormGroup({
        'cardNumber': new FormControl(),
        'expiry': new FormControl(),
        'cvv': new FormControl('',[NoWhitespaceValidator]),
      },OneFilledOutValidator)
    });

//验证文件

import {FormControl, FormGroup, AbstractControl, ValidatorFn} from '@angular/forms';
import {Observable} from 'rxjs/Observable';

export const OneFilledOutValidator = (): ValidatorFn => {

  return (group: FormGroup): {[key: string]: boolean} => {

    const fields = [];

    for (const field in group.controls) {

      if (group.controls.hasOwnProperty(field)) {
        fields.push(group.get(field).value);
      }
    };

    const result = fields.filter(field => !!field);

    const valid = result.length !== 0;
    console.log(valid);
    return valid ? null : {
      oneFilledOut: true
    };
  };
};

export function NoWhitespaceValidator(): ValidatorFn {

  return (control: AbstractControl): { [key: string]: any } => {

    let isWhitespace = (control.value || '').trim().length === 0;
    let isValid = !isWhitespace;
    console.log(isValid);
    return isValid ? null : { 'whitespace': 'value is only whitespace' }

  };
}

但是没有一个验证器对我有用。

谁能为此提出一个好的起点?我该如何实施?
在此正常验证之后,我还需要根据卡号、到期等的常见卡验证来检查卡字段是否真的有效,因此提出相应的建议。

【问题讨论】:

  • 您可以在输入字段中使用模式

标签: angular angular-reactive-forms custom-validators formgroups


【解决方案1】:

这里有一些错误:

  1. 在函数(): ValidatorFn中包装验证器
  2. 群组需要使用{ validators: OneFilledOutValidator }

此处示例:https://stackblitz.com/edit/angular-gacawd?file=app%2Fapp.component.ts

【讨论】:

  • 感谢您提供起点。我已根据我的要求对其进行了如下修改:stackblitz.com/edit/angular-o23c8o?file=app%2Fapp.component.ts
  • 只有在当前空类型验证有效的情况下,是否有关于进行条件验证检查的参考,例如检查信用卡验证。
  • 目前我已经在表单组上添加了更改事件,并根据表单状态动态添加了验证。如果您有更好的想法,请告诉我。
  • 找不到页面。
猜你喜欢
  • 1970-01-01
  • 2019-01-07
  • 1970-01-01
  • 2018-05-23
  • 2018-01-26
  • 1970-01-01
  • 2020-07-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多