FormGroup async validator not called if FormContro

2019-05-23 01:22发布

I've wrote an async validator for a specific field an another one for 2 fields of the form:

this.aliasCtrl = formBuilder.control('', [], [
  (control: AbstractControl) => {
    return new Promise(resolve => {
      if(control.value === 'aaa') {
        resolve({error: true});
      } else {
        resolve(null);
      }
    });
  }
]);

this.formGroup = formBuilder.group({
  firstName: formBuilder.control('', []),
  lastName: formBuilder.control('', []),
  alias: this.aliasCtrl
}, {
  asyncValidator: (group: FormGroup) => {
    return new Promise(resolve => {
      if(group.value.firstName === 'aaa' && group.value.lastName === 'aaa') {
        resolve({error2: true});
      } else {
        resolve(null);
      }
    });
  }
});

Both of them are working correctly. The point is, when the alias control validator throws an error (when the field contains aaa), the "global" one never does.

A plunker of my issue: http://plnkr.co/edit/vyr48ke7fWEUwrXy43tn?p=preview

How to reproduce:

  1. put aaa in all fields starting with the first one. Good, everything works.
  2. Reload the plunker.
  3. put aaa in all fields starting with the last one. The "global" validator is not called when editing firstName of lastName field (I've added some console.log in the plunker to watch when validators are called).

Is the behaviour intentional? Why? How to call the "global" validator event if an error already exists?

1条回答
▲ chillily
2楼-- · 2019-05-23 01:45

One way to answer my question is to define a formGroup containing fields firstName and lastName. Here's a plunker with the solution: http://plnkr.co/edit/HAmaYySbxVE15VOl9uJ4?p=preview

For reference, I let here my formGroup:

this.aliasCtrl = formBuilder.control('', [], [(control: AbstractControl) => {
    return new Promise(resolve => {
      if(control.value === 'aaa') {
        resolve({error: true});
      } else {
        resolve(null);
      }
    });
  }
]);

this.nameGroup = formBuilder.group({
  firstName: formBuilder.control('', []),
  lastName: formBuilder.control('', [])
}, {
  asyncValidator: (group: FormGroup) => {
    return new Promise(resolve => {
      if(group.value.firstName === 'aaa' && group.value.lastName === 'aaa') {
        resolve({error2: true});
      } else {
        resolve(null);
      }
    });
  }
});

this.formGroup = formBuilder.group({
  name: this.nameGroup,
  alias: this.aliasCtrl
});
查看更多
登录 后发表回答