动态添加表单验证

时间:2016-06-06 12:45:19

标签: angular

我必须在表单中添加验证,只有当有人开始输入其中一个输入时。这将是一个基本的验证,只需要所有输入。如何以最简单的方式实现这一目标。

1 个答案:

答案 0 :(得分:0)

ngOnInit(){
   this.setUserCategoryValidators()
}

Candidateform = this.fb.group({
    Name: ['', Validators.required],
    Gender: ['', Validators.required],
    Nationality: ['', Validators.required],
    DOB: ['', Validators.required],
    Profession: ['', Validators.required],
    EmailId: ['', Validators.email],


    DrivingLicense: [''],
    DrivingLicenseFile: [''],
    GccLicense: [''],
    GccLicenseFile: [''],
  })

setUserCategoryValidators() {
    debugger;
    const DrivingLicenseFile = this.Candidateform.get('DrivingLicenseFile');
    const GccLicenseFile = this.Candidateform.get('GccLicenseFile');

    this.Candidateform.get('DrivingLicense').valueChanges
      .subscribe(drivingLicense => {

        if (drivingLicense == true)
          DrivingLicenseFile.setValidators([Validators.required]);

        if (drivingLicense == false)
          DrivingLicenseFile.setValidators(null);

        DrivingLicenseFile.updateValueAndValidity();
      });

    this.Candidateform.get('GccLicense').valueChanges
      .subscribe(gccLicense => {

        if (gccLicense == true)
          GccLicenseFile.setValidators([Validators.required]);

        if (gccLicense == false)
          GccLicenseFile.setValidators(null);

        GccLicenseFile.updateValueAndValidity();
      });
  }