如何在Angular2中触发表单验证器

如何在Angular2中触发表单验证器

在Angular 2中,处理复杂表单的最好方法是使用反应式表单。下面我们将详细说明如何触发登录页面的表单验证器。

在反应式表单中,我们使用FormControl,通过使用它,我们可以访问表单的子字段和它们的属性。它们的一些属性是dirty, touched, untouched, pristine, valid, errors等。使用这些属性,我们实际上可以根据需求来触发验证。

  • dirty。如果用户将子字段的值从默认值中改变,则该属性被激活。
  • touched。如果用户访问了该子字段,那么触摸的属性值就被设置为 “true”。
  • untouched。如果用户没有访问子字段,那么untouched属性值被设置为 “true”。它与触及的属性完全相反。
  • pristine。如果用户访问该子字段并且没有对其值进行任何改变,那么它就被设置为 “true”。
  • valid。如果该表格满足所有的表格验证,那么它将是 “true”。
  • errors。Angular在客户端生成一个错误列表,其中包含所有内置的错误,如required、maxLength、pattern、minLength等等。

使用以上讨论的属性,我们可以通过自定义消息来触发表单验证。使用每个子字段的FormControl,并检查它的属性,如已触摸、脏等,我们可以根据需要对表单进行验证。

步骤:

  • 首先,根据.html文件,在component.ts文件中添加所有的表单控件。
  • 然后在component.ts文件中为所需的子字段添加验证信息,例如。要求,最大长度,模式,等等。
  • 确保你从’angular@/forms’中导入了Validators的所有内容
  • 然后在.html文件中添加验证信息,如下代码所示。
  • 同时,在模块文件中从’angular@/material’导入所有的依赖项。

为了获得更好的动画和造型,angular提供了Angular material,它有关于造型的丰富信息。使用angular material,表单是有风格的。因此,我们使用了<mat-form-field><mat-error><mat-label>matInput等标签。

我们可以在使用npm安装angular material后从其导入。导入的命令如下。

ng add @angular/material

代码实现:下面是上述方法的实现。

app.module.ts:

import { BrowserModule } from 
        '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from 
        '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } 
        from '@angular/forms';
import { MatInputModule } from 
        '@angular/material/input';
import { MatDialogModule } from 
        '@angular/material/dialog';
import { MatFormFieldModule } from 
        '@angular/material/form-field';
import { MatIconModule } from 
        '@angular/material/icon';
  
@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        FormsModule,
        ReactiveFormsModule,
        BrowserAnimationsModule,
        MatInputModule,
        MatFormFieldModule,
        MatIconModule,
        MatDialogModule,
    ],
    bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts:

import { Component, OnInit } 
        from '@angular/core';
  
// Imports
import { FormGroup, FormControl, 
    Validators } from '@angular/forms';
  
  
@Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  
    constructor() { }
  
    ngOnInit() {
    }
  
    profile = new FormGroup(
        {
            // Setting Validation Controls
            email: new FormControl('', 
                [Validators.required, 
                Validators.minLength(8),
                Validators.pattern(
/^\w+@[a-z0-9A-Z_]+?\.[a-zA-Z]{2, 5}/)]),
                password: new FormControl('', 
                [Validators.required, 
                Validators.minLength(8),
                Validators.pattern(
/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@!%*?&])[A-Za-z\d@!%*?&]{8, }/)])
        }
    );
}

app.component.html:

<div class="container-fluid">
  <div class="row">
    <div class="col-12 col-sm-6 
              col-md-6 col-lg-12">
  
      <h4>Login to start</h4>
  
      <form [formGroup]="profile">
  
        <mat-form-field appearance="outline">
          <mat-label>Email</mat-label>
          <input type="email" matInput 
            placeholder="Enter Email" 
            formControlName="email">
  
          <mat-error *ngIf=
"profile.controls['email'].errors?.pattern && profile.controls['email'].touched">
            Enter a valid email with 
            requested pattern
          </mat-error>
  
          <mat-error *ngIf=
"profile.controls['email'].errors?.minLength && profile.controls['email'].touched">
            Email should have minimum 
            8 characters
          </mat-error>
  
          <mat-error *ngIf=
"profile.controls['email'].errors?.required && profile.controls['email'].touched">
            Email is required
          </mat-error>
        </mat-form-field>
  
        <mat appearance="outline">
          <mat-label>Password</mat-label>
          <input matInput type="password" 
            placeholder="Enter password" 
            formControlName="password">
  
          <mat-error *ngIf=
"profile.controls['password'].errors?.required && profile.controls['password'].touched">
            Password is required
          </mat-error>
  
          <mat-error *ngIf=
"profile.controls['password'].errors?.minLength && profile.controls['password'].touched">
            Enter a password with 
            more than 8 letters
          </mat-error>
  
          <mat-error *ngIf=
"profile.controls['password'].errors?.pattern && profile.controls['password'].touched">
            Enter a password with 
            valid pattern
          </mat-error>
        </mat - form - field>
  
        <button class="btn btn-primary" 
          [disabled]="!profile.valid"> 
          Submit
        </button>
      </form>
    </div>
  </div>
</div>

输出:因此,我们已经成功触发了表单验证。

如何在Angular2中触发表单验证器?

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程