【问题标题】:Angular 6 and Ionic 3 reactive form validation error not displayAngular 6 和 Ionic 3 反应式表单验证错误不显示
【发布时间】:2019-02-20 14:26:06
【问题描述】:

我正在开发一个使用最新版本的 Angular 和 Ionic 的项目。我正在注册页面上工作。当表单输入无效时,我需要显示一些错误。我在我的项目中使用 Angular Reactive 表单,但如果我在页面上检查错误,它不会显示。它只显示红色下划线,但我需要显示一些可读错误

这是我的查看代码

<ion-content padding>
  <ion-list class="items-middle" text-center>
    <!-- use the [formGroup] directive to tell Angular that we want to use the registrationForm as the "FormGroup" for this form: -->
    <form [formGroup]="registrationForm">
      <ion-item>
        <ion-label floating>Full Name</ion-label>
        <ion-input type="text" formControlName="userName"></ion-input>
        <div *ngIf="!registrationForm.controls['userName'].valid && registrationForm.controls['userName'].touched"> name is required</div>
      </ion-item>
      <!-- <ion-item>
                <ion-label color="ligh-grey" floating>Email</ion-label>
                <ion-input type="email" formControlName="email"></ion-input>
            </ion-item>
            <ion-item>
                <ion-label color="ligh-grey" floating>Date of Birth</ion-label>
                <ion-input type="text" formControlName="dob"></ion-input>
            </ion-item>
            <ion-item>
                <ion-label color="ligh-grey" floating>Phone Number</ion-label>
                <ion-input type="number" formControlName="phone" pattern="[0-9]*"></ion-input>
            </ion-item>
            <ion-item>
                <ion-label color="ligh-grey" floating>Address</ion-label>
                <ion-input type="text" formControlName="address"></ion-input>
            </ion-item>
            <ion-item class="job_status">
                <ion-label color="ligh-grey" floating>Job Status (Position)</ion-label>
                <ion-input type="text" formControlName="jobStatus"></ion-input>
            </ion-item>
            <ion-item>
                <ion-label>Job Sector</ion-label>
                <ion-select formControlName="jobSectore">
                    <ion-option value="f">Government</ion-option>
                    <ion-option value="m">Private</ion-option>
                </ion-select>
            </ion-item>
            <input type="checkbox" formControlName="isTosRead"> -->
      <!-- We can check if our form is valid: -->
      <ion-buttons padding-top>
        <button ion-button full round type="submit" [disabled]="!registrationForm.valid">SIGNUP</button>
      </ion-buttons>
    </form>
    <pre> {{registrationForm.status}}</pre>
    <pre> {{registrationForm.value | json }}</pre>
  </ion-list>
</ion-content>

这是我的 TS 文件

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@IonicPage()
@Component({
  selector: 'page-registration',
  templateUrl: 'registration.html',
})
export class RegistrationPage {

  registrationForm: FormGroup;
  userName: string;

  constructor(public navCtrl: NavController, public navParams: NavParams, private fb: FormBuilder) {
    // this.registrationForm = new FormGroup({
    //   userName: new FormControl('', [Validators.required, Validators.minLength(2), Validators.pattern('^[a-zA-Z]+$')]),
    //   email: new FormControl('', [Validators.required, Validators.email, Validators.minLength(4)]),
    //   dob: new FormControl('', [Validators.required, Validators.minLength(4)]),
    //   phone: new FormControl('', [Validators.required, Validators.minLength(9), Validators.maxLength(10)]),
    //   address: new FormControl('', [Validators.required, Validators.minLength(9), Validators.maxLength(255)]),
    //   jobStatus: new FormControl('', [Validators.required, Validators.minLength(2), Validators.maxLength(50)]),
    //   jobSectore: new FormControl('', [Validators.required]),
    //   isTosRead: new FormControl(false, [Validators.requiredTrue])
    // })

    this.registrationForm = this.fb.group({
      'userName': [null, Validators.compose([Validators.pattern('^[a-zA-Z]+$'), Validators.required])]
    });
  }
}

这里到底出了什么问题?为什么我没有收到*ngIf 条件,控制台没有显示任何错误。

【问题讨论】:

  • 我认为您已经涵盖了两个条件,例如 *ngIf="!(registrationForm.controls['userName'].valid && registrationForm.controls['userName'].touched)"跨度>
  • 所以你的意思是我需要单独检查它们?
  • 目前如果你提交是不是显示不需要?
  • @SahanPasinduNirmal 因为你有touched 在具有&amp;&amp; 条件的字段上,你必须触摸该字段才能看到错误。
  • registrationForm.get('userName') 应该将 formControl 返回给您

标签: javascript angular ionic3


【解决方案1】:

尝试如下改变条件,

this.registrationForm = this.fb.group({
      userName: [
        null, Validators.compose([Validators.maxLength(30), Validators.pattern('^[a-zA-Z]+$'), Validators.required])
      ],

编辑

也改变你的模板如下,

<ion-item *ngIf="!registrationForm .controls.userName.valid && (registrationForm .controls.userName.dirty)"> <p>Please enter a valid name.</p> </ion-item> 

【讨论】:

  • 感谢您的努力和善意的考虑,先生,但它向我显示了相同的输出,没有任何基于文本的视觉错误。 :(
  • 哦!试试这个

    请输入一个有效的名字。

  • @PankajParkar 是的,你是对的!这里唯一的区别是我使用了点操作而不是 OPs 方式。使用 touch 仍然可以工作
  • @SahanPasinduNirmal 是的,这是另一个错误。你应该在离子项目上使用条件
  • @PankajParkar 是的,没有区别,两种方式都有效
【解决方案2】:

在您的 formControl 中添加 &lt;span&gt; 标签,如下所示:

或在您当前的&lt;div&gt; 中添加class="text-danger"

.html 文件。

显示required错误信息

<span class="text-danger" *ngIf="registrationForm.controls['userName'].hasError('required') && (registrationForm.controls['userName'].dirty || registrationForm.controls['userName'].touched)">Field is required</span>

显示pattern错误信息

<span class="text-danger" *ngIf="registrationForm.controls['userName'].hasError('pattern') && (registrationForm.controls['userName'].dirty || registrationForm.controls['userName'].touched)">Enter valid username.</span>

ts 文件。

this.registrationForm = this.fb.group({
  'userName': [null, Validators.compose([Validators.pattern('^[a-zA-Z]+$'), Validators.required])]
});

【讨论】:

  • 感谢您的努力和善意的考虑,先生,但结果是一样的
  • 使用p标签代替span标签。
  • 没有兄弟这是问题我没有设置这样的控件对象名称=>“!registrationForm.controls.userName.valid”现在它正在工作
  • 好吧,太好了。
  • !registrationForm.controls.userName.valid 确实有效。但是,如果您想显示与尝试我给出的答案不同的错误消息。前任。在你的情况下。您对同一控件有两个验证。喜欢patternrequired。您可以使用 hasError('pattern')hasError('required')
【解决方案3】:

您必须在 ion-item 标记之外添加错误消息 div,如下所示:

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>
  <ion-list class="items-middle" text-center>
    <form [formGroup]="registrationForm">
      <ion-item>
        <ion-label floating>Full Name</ion-label>
        <ion-input type="text" formControlName="userName"></ion-input>
      </ion-item>
      <div *ngIf="registrationForm.get('userName').touched && registrationForm.get('userName').invalid"> name is required</div>
      <ion-buttons padding-top>
        <button ion-button full round type="submit" [disabled]="!registrationForm.valid">SIGNUP</button>
      </ion-buttons>
    </form>
    <pre> {{registrationForm.status}}</pre>
    <pre> {{registrationForm.value | json }}</pre>
    <pre> {{registrationForm.get('userName').invalid | json }}</pre>
    <pre> {{registrationForm.get('userName').touched | json }}</pre>
  </ion-list>
</ion-content>

另外,您可以简单地使用registrationForm.get('userName').touched &amp;&amp; registrationForm.get('userName').invalid"&gt;

这是Sample StackBlitz

【讨论】:

  • 谢谢您的代码也对我有用,先生,我的错误是将 div 标签放在 标签内?
  • 是的,我猜。我会使用registrationForm.get('userName') 而不是registrationForm.controls['userName']
  • 先生,.get() 方法有什么特别之处吗?
  • 您可能想为此阅读:stackoverflow.com/a/49643393/2622292
  • 帮了大忙,先生。
猜你喜欢
  • 2020-09-07
  • 2019-03-13
  • 2018-01-02
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2018-09-22
  • 2019-12-01
  • 1970-01-01
相关资源
最近更新 更多