提交时对字段的条件验证

Conditional validation for a field on submit

有条件地向提交时的“imageString”字段添加必需的验证。但它没有按预期设置所需的验证。

正在初始化表单。

constructor(){
 this.poeForm = this.fb.group({
      imageString: [""],
      imageFileName: [""],
    }
 }
}

已调用保存,为 imageString 字段设置验证。

   saveForm() {
       this.profileImgValidator();
       this.getFormValidationErrors();
       if (this.poeForm.invalid) {
          Swal.fire("Please fill in all the required fields");
          return;
        }
      }

设置值的实际逻辑。

 profileImgValidator(){
    let errors = null;
    this.mandatoryFields = //server call it will return value or null
    if(this.mandatoryFields){     
        this.poeForm.get('imageString').setValidators(Validators.required);
      }else{
        this.poeForm.get('imageString').clearValidators();
      }    
    return errors;
  }

通过遍历表单控件进行检查。

 getFormValidationErrors() {
    Object.keys(this.poeForm.controls).forEach(key => {
    const controlErrors: ValidationErrors = this.poeForm.get(key).errors;
    if (controlErrors != null) {
          Object.keys(controlErrors).forEach(keyError => {
            console.log('Key control: ' + key + ', keyError: ' + keyError + ', err value: ', controlErrors[keyError]);
          });
        }
      });
    }

尝试以下操作:

profileImgValidator() {
  let errors = null;
  this.mandatoryFields = //server call it will return value or null
  
  const item = this.poeForm.get('imageString');
  if (this.mandatoryFields) {
    item.clearValidators();
    item.setValidators(Validators.required);
  } else {
    item.clearValidators();
  }

  item.updateValueAndValidity();
  this.poeForm.updateValueAndValidity();

  return errors;
}

Angular Reactive Form 有一个 custom validators,在这里使用它非常有意义。

this.poeForm = this.fb.group({
  imageString: [""],
  imageFileName: [""],
 }, { validators: profileImgValidator } // use custom validator
}

export const profileImgValidator: ValidatorFn = (control: FormGroup): ValidationErrors | null => {
 const imageString = control.get('imageString').value;

 if (this.mandatoryFields) {
   return imageString ? null : { required: true }
 }

 return null;
};