角度反应形式根据另一个字段的值有条件地验证字段

24s*_*ron 3 angular-validation angular angular-reactive-forms

这是我的代码

detailsGroup = new FormGroup({
    userId:new FormControl('1'),
    firstName: new FormControl('', Validators.required),
    lastName: new FormControl('', Validators.required),
    email: new FormControl('',[ Validators.required, Validators.email]),
  });
Run Code Online (Sandbox Code Playgroud)

我希望如果userId equal to 1名字、姓氏和电子邮件不需要, otherwise这 3 个字段将更改为必填,并且电子邮件还验证电子邮件地址。

谢谢

vic*_*oob 5

您应该编写一个自定义验证器,如下所示:演示:https: //angular-custom-validator-p2u1jv.stackblitz.io

function nameValidator(form: FormGroup): ValidatorFn {
  return (control: AbstractControl): ValidationErrors | null => {
    const needRequire = form.get('userId').value != 1
    const noValue = needRequire ? !(control.value) : false
    return noValue ? {required: control.value} : null;
  };
}
this.form = new FormGroup({
  userId:new FormControl('1'),
  firstName: new FormControl(''),
  lastName: new FormControl(''),
  email: new FormControl('',[ Validators.required, Validators.email]),
});

this.form.get('firstName').setValidators(nameValidator(this.form))
this.form.get('lastName').setValidators(nameValidator(this.form))
Run Code Online (Sandbox Code Playgroud)