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>
app.component.css
*{
font-size: 18px;
}
.wrapper{
margin: 0 auto;
margin-top:10%;
width:30%;
height: 20%;
border:1px solid black;
border-radius: 10px;
}
.title-wrapper{
margin: 0 auto;
padding-top: 20px;
padding-bottom: 20px;
width:370px;
text-align: center;
font-size: 20px;
font-weight: 800;
}
label{
display: inline-block;
width:72px;
}
.contain-wrapper{
width: 300px;
margin:0 auto;
}
.confirm{
margin-top:20px;
width:100%;
}
3.项目效果
二、自定义验证
自定义表单验证,需要创建自定义验证器,我们接下来更改邮箱的验证,将其改为有格式的验证,而不是单纯的存在验证,首先我们来看一下项目目录的更改
1.项目目录
----------app.component.ts
----------app.component.html
----------app.component.css
----------app.module.ts
----------emailAuthentication.ts
2.项目代码
app.module.ts
注册自定义验证器EmailValidatorDirective
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule,ReactiveFormsModule } from '@angular/forms';
import { EmailValidatorDirective } from './emailAuthentication';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent,
EmailValidatorDirective
],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
emailAuthentication.ts
import { Directive, Input, OnChanges, SimpleChanges } from '@angular/core';
import { AbstractControl, NG_VALIDATORS, Validator, ValidatorFn, Validators } from '@angular/forms';
/** A hero's name can't match the given regular expression */
export function emailValidator(nameRe: RegExp): ValidatorFn {
return (control: AbstractControl): { [key: string]: any } => {
const forbidden = !nameRe.test(control.value);
return forbidden "htmlcode">
import { Component,OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { emailValidator } from './emailAuthentication'; //导入emailValidator自定义验证器
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app';
//email的正则表达式
emailExp = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/ ;
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,
emailValidator(this.emailExp) //自定义验证器
]),
'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'); }
}
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" required><br/>
<div *ngIf="email.invalid && (email.dirty || email.touched)" class="alert alert-danger">
<div *ngIf="email.errors.forbiddenName">
请输入正确格式的邮箱!
</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" [disabled]="Form.invalid" >确认</button>
</div>
</div>
在最后确认的时候,我们设置一下按钮的disabled属性,在表单验证不通过的时候,确认按钮是点击不了的,显示不可点击状态。[disabled]="Form.invalid"。
3.项目效果
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
Angular,表单验证
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新动态
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]


