angular 需要根据条件对表单进行验证

angular required validations on forms based on conditions

我的代码中有一部分只根据需要设置一些字段。默认情况下只有 emailAddress 是必填字段,但我的应用程序中有条件根据需要设置 firstName 、 lastName 、 companyName 。

如果res.isSuccess === true 那时候我只想按要求设置名字,姓氏,公司名称。

但问题是,正如您在下面的屏幕显示中看到的那样,mat 错误消息已经在初始加载时显示(红色的)它应该只显示例如 firstname 字段被触摸或点击所以消息应该默认不显示。

大家对这个问题有什么想法吗?谢谢。

#html

 <mat-form-field class="full-width" appearance="fill" style="margin-top: 26px;">
                                <mat-label>First Name *</mat-label>
                                <input matInput formControlName="firstName">
                                <mat-error
                                    *ngIf="modelForm.get('firstName').hasError('required')  && (modelForm.get('firstName').touched || modelForm.get('firstName').dirty)">
                                    First Name is required.
                                </mat-error>
                            </mat-form-field>

     getStarted() {
        this.AccountRoleDetails = null;
        if (this.userService) {
          this.userService
            .getUserEmail(this.accountId, this.modelForm.value['emailAddress'])
            .subscribe(
              (res: any) => {
                if (
                  res.isSuccess === true 
                ) 
              this.setRequiredVlidations();
    
    
    {
.........

#代码

initFormGroup() {
    this.modelForm = this.formBuilder.group({
      id: [this.model.id || 0],
      emailAddress: [this.model.emailAddress, Validators.required],
      firstName: this.model.firstName,
      roleId: this.model.roleId,
      lastName: this.model.lastName,
      phoneNumber: this.model.phoneNumber,
      companyName: this.model.companyName,
    });
  }

#代码 2

setRequiredVlidations() {
    this.modelForm.get('firstName').setValidators(Validators.required);
    this.modelForm.get('lastName').setValidators(Validators.required);
    this.modelForm.get('companyName').setValidators(Validators.required);

    this.modelForm.updateValueAndValidity();
  }

尝试取出

this.modelForm.updateValueAndValidity();

这可能会导致 Angular 响应式表单检查值,如果它是空的,如果它是“必需的”则将无效。

在你的 mat-error html 标签中,尝试分离出逻辑树以便更清晰:

<mat-error *ngIf="(modelForm.get('firstName').hasError('required') && 
    modelForm.get('firstName').touched) || 
    modelForm.get('firstName').dirty">
        First Name is required.
</mat-error>

您也可以尝试在此处更改您的逻辑:

<mat-error *ngIf="modelForm.controls.firstName.invalid &&
                  modelForm.controls.firstName.dirty">
        First Name is required.
</mat-error>

或:

<mat-error *ngIf="modelForm.controls.firstName.invalid &&
                  modelForm.controls.firstName.touched">
        First Name is required.
</mat-error>

取决于您的 UI/UX 要求。

这将帮助您更清楚地了解返回无效状态的确切原因。使用浏览器控制台并进行一些检查。

也尝试使用您的浏览器工具实际查看表单字段验证错误和值以及该字段在设置新验证器之前和之后的有效性状态。 “必需”状态的访问方式可能与您正在执行的方式不同。

你能 post 这些从浏览器控制台获得的值并更新你的问题吗?