Angular表单验证分为两种验证:1.内置验证(required,minlength等);2.自定义验证(正则表达式)。
接下来我们用一个注册账号的demo来看一下这两种验证是如何实现的。
项目界面
一、内置验证
其中账户名有required验证和最短长度验证,其他两个只有required验证
1.项目目录
----------app.component.ts
----------app.component.html
----------app.component.css
----------app.module.ts
2.项目代码
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule,ReactiveFormsModule } from '@angular/forms';//表单验证必须导入这两个模块 import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, FormsModule, //注册模块 ReactiveFormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
app.component.ts
import { Component,OnInit } from '@angular/core'; import { FormGroup, FormControl, Validators } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { title = 'app'; Form:FormGroup; data={ name:"", email:"", tel:"" } ngOnInit(): void { this.Form = new FormGroup({ 'name': new FormControl(this.data.name, [ Validators.required, Validators.minLength(4) ]), 'email': new FormControl(this.data.email, Validators.required), 'tel': new FormControl(this.data.tel, Validators.required) }); } get name() { return this.Form.get('name'); } get email() { return this.Form.get('email'); } get tel() { return this.Form.get('tel'); } }
简单来说,在使用验证表单的时候,大致分为四步:
(1)导入相关模块FormGroup, FormControl, Validators;
(2)声明表单验证变量From:FromGroup;
(3)定义验证规则;
(4)通过它所属的控件组(FormGroup)的get方法来访问表单控件
app.component.html
<div class="wrapper"> <div class="row"> <p class="title-wrapper">注册账号</p> </div> <div class="row"> <div class="contain-wrapper" [formGroup]="Form"> <label for="name">账户名:</label> <input type="text" id="name" formControlName="name"><br/> <div *ngIf="name.invalid && (name.dirty || name.touched)" class="alert alert-danger"> <div *ngIf="name.errors.required"> 请输入长度账户名! </div> <div *ngIf="name.errors.minlength"> 账户名长度不小于4! </div> </div> <label for="email">邮箱:</label> <input type="text" id="email" formControlName="email"><br/> <div *ngIf="email.invalid && (email.dirty || email.touched)" class="alert alert-danger"> <div *ngIf="email.errors.required"> 请输入邮箱! </div> </div> <label for="tel">电话:</label> <input type="text" id="tel" formControlName="tel"> <div *ngIf="tel.invalid && (tel.dirty || tel.touched)" class="alert alert-danger"> <div *ngIf="tel.errors.required"> 请输入电话! </div> </div> </div> </div> <div class="row"> <button class="btn btn-primary confirm">确认</button> </div> </div>
内容版权声明:除非注明,否则皆为本站原创文章。