如何在Angular 6中一一验证输入字段

时间:2018-09-20 04:34:21

标签: angular typescript angular5 angular6

我在这里刚开始尝试验证一个小表格。在这种情况下,一切都很好。

我想做的是,如果用户单击“保存”按钮而不触摸表单字段,我只想在第一个字段而不是所有字段中显示错误消息。

现在,它在所有字段中显示错误消息,破坏了外观。

因此,如果用户单击“保存”按钮而未在表单中输入任何内容,那么如何在第一次提交时显示错误消息。如果用户在第二个字段中输入内容并单击“保存”按钮,它将在第一个字段中首先显示错误消息,如果再次单击“保存”按钮,则应该在第三个字段上显示错误消息,因为第二个字段之前已经过验证。

app.component.ts

export class InputErrorStateMatcherExample {
  userAddressValidations: FormGroup;
  constructor(private formBuilder: FormBuilder) { }
  ngOnInit() {
    this.userAddressValidations = this.formBuilder.group({
      firstName: ['', [Validators.required, Validators.minLength(4), Validators.maxLength(20), Validators.pattern('[a-zA-Z]+')]],
      lastName: ['', [Validators.required, Validators.minLength(4),Validators.maxLength(20)]],
       location: ['', [Validators.required, Validators.minLength(4),Validators.maxLength(20)]]
    });

  }
}

app.component.html

<form class="example-form" [formGroup]="userAddressValidations">
    <mat-form-field class="example-full-width">
        <input matInput placeholder="First Name" formControlName="firstName">
        <mat-error *ngIf="userAddressValidations.get('firstName').hasError('required')">
            First Name is Required!
        </mat-error>
        <mat-error *ngIf="userAddressValidations.get('firstName').hasError('minlength')">
            First Name should be atleast 4 characters long!
        </mat-error>

        <mat-error *ngIf="userAddressValidations.get('firstName').hasError('maxlength')">
            First Name can be atmax n characters long!
        </mat-error>

        <mat-error *ngIf="userAddressValidations.get('firstName').hasError('pattern')">
            First Name must follow this pattern!
        </mat-error>
    </mat-form-field>

    <mat-form-field class="example-full-width">
        <mat-label>Last Name</mat-label>
        <input matInput formControlName="lastName">
        <mat-error *ngIf="userAddressValidations.get('lastName').hasError('required')">
            Please fill out this field.
        </mat-error>
        <mat-error *ngIf="userAddressValidations.get('lastName').hasError('minlength')">
            Minimum 4 characters required.
        </mat-error>
        <mat-error *ngIf="userAddressValidations.get('lastName').hasError('maxlength')">
            Accepts only 20 characters.
        </mat-error>
    </mat-form-field>

    <mat-form-field class="example-full-width">
        <mat-label>Location</mat-label>
        <input matInput formControlName="lastName">
        <mat-error *ngIf="userAddressValidations.get('location').hasError('required')">
            Please fill out this field.
        </mat-error>
        <mat-error *ngIf="userAddressValidations.get('location').hasError('minlength')">
            Minimum 4 characters required.
        </mat-error>
        <mat-error *ngIf="userAddressValidations.get('location').hasError('maxlength')">
            Accepts only 20 characters.
        </mat-error>
    </mat-form-field>

    <button mat-raised-button  color="warn">
      <span>Save</span>
  </button>
</form>

Stackblitz:https://stackblitz.com/edit/angular-mat-form-validation-eg-avw2qh?file=app%2Finput-error-state-matcher-example.html

任何人都可以帮助我以有效的方式做到这一点。

谢谢。

1 个答案:

答案 0 :(得分:0)

我同意@LazarLjubenović的观点,这是一个坏主意。但是,如果这是您真正想要的...

我将添加一个提交方法,如下所示:

<form class="example-form" [formGroup]="userAddressValidations" (ngSubmit)="onSubmit()">

,然后在Submit方法中执行以下操作:

onSubmit() {
  const props = Object.keys(this.userAddressValidations.value)
  this.firstError = null
  props.forEach((prop) => {
    if (!this.firstError && this.userAddressValidations.get(prop).errors) {
      console.log('setting firstError', prop, this.userAddressValidations.get(prop).errors)
      this.firstError = prop
    }
  })
  console.log('firstError', this.firstError)
}

这将在字符串中存储错误的第一个字段的名称。

然后将HTML错误消息更改为以下内容:

<mat-error *ngIf="userAddressValidations.get('firstName').hasError('required') && firstError === 'firstName'">
    First Name is Required!
</mat-error>

这个问题可能需要做一些调整才能完成实现,但是您会发现一个大概的想法。