我們會在本文中探索 Angular 2 內(nèi)建的自定義驗證。
# 介紹
Angular 2 原生就支持一些有用的驗證器:
我們會基于下面的接口創(chuàng)建一個表單來獲取用戶信息。
// user.interface.tsexport interface User { username: string; // required, must be 5-8 characters email: string; // required, must be valid email format password: string; // required, value must be equal to confirm password. confirmPassword: string; // required, value must be equal to password.}需求
僅在字段數(shù)據(jù)不正確或提交表單的時候,為每個字段 顯示錯誤消息 。
UI 展示:
# App 配置
這是我們的文件結(jié)構(gòu):
|- app/ |- app.component.html |- app.component.ts |- app.module.ts |- equal-validator.directive.ts |- main.ts |- user.interface.ts|- index.html|- styles.css|- tsconfig.json
為了使用新的表單模塊,我們需要用 npm install @ angular/forms 指令調(diào)用 npm 包,并在應(yīng)用程序模塊中導(dǎo)入最新的表單模塊。
$ npm install @angular/forms --save
下面是我們應(yīng)用程序的 app.module.ts 模塊:
// app.module.tsimport { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { AppComponent } from './app.component';@NgModule({ imports: [ BrowserModule, FormsModule ], // import forms module here declarations: [ AppComponent ], bootstrap: [ AppComponent ],})export class AppModule { }# App 組件
讓我們繼續(xù)創(chuàng)建 App 組件。
// app.component.tsimport { Component, OnInit } from '@angular/core';import { User } from './user.interface';@Component({ moduleId: module.id, selector: 'app-root', templateUrl: 'app.component.html', styleUrls: ['app.component.css']})export class AppComponent implements OnInit { public user: User; ngOnInit() { // initialize model here this.user = { username: '', email: '', password: '', confirmPassword: '' } } save(model: User, isValid: boolean) { // 調(diào)用API保存customer console.log(model, isValid); }}# HTML 視圖
這是我們的 HTML 視圖的樣子。
<!-- app.component.html --><div> <h1>Add user</h1> <form #f="ngForm" novalidate (ngSubmit)="save(f.value, f.valid)"> <!-- 我們將把驗證的字段放在這里 --> <button type="submit" [disabled]="!myForm.valid">Submit</button> </form></div>
現(xiàn)在來一個個添加控件。
用戶名
需求: 必填,長度在 5-8 個字符之間
<!-- app.component.html -->...<div> <label>Username</label> <input type="text" name="username" [ngModel]="user.username" required minlength="5" maxlength="8" #username="ngModel"> <small [hidden]="username.valid || (username.pristine && !f.submitted)"> Username is required (minimum 5 characters). </small></div><pre *ngIf="username.errors">{{ username.errors | json }}</pre>...required、minlength、maxlength 都是內(nèi)置的驗證器,所以很容易使用。
我們只會在用戶名無效、獲得焦點和提交表單的情況下顯示錯誤消息。最后一條的 pre 標(biāo)簽在開發(fā)過程中對調(diào)試很有用。它會顯示字段的所有驗證錯誤。
電子郵件地址
需求: 必填,必須是有效的電子郵件地址格式
<!-- app.component.html -->...<div> <label>Email</label> <input type="email" name="email" [ngModel]="user.email" required pattern="^[a-zA-Z0 主站蜘蛛池模板: 平陆县| 武山县| 枣强县| 凌源市| 岱山县| 涞源县| 南溪县| 四子王旗| 大田县| 东乡| 奉贤区| 广宗县| 黑河市| 宁海县| 达孜县| 武胜县| 瑞昌市| 乐亭县| 开远市| 泗阳县| 巴楚县| 枞阳县| 景洪市| 阿瓦提县| 开平市| 柞水县| 黄龙县| 东平县| 铁岭县| 曲靖市| 常州市| 宜黄县| 上高县| 舒城县| 聂荣县| 张北县| 和龙市| 广德县| 抚顺县| 揭东县| 波密县|