1什麼是模板驗證
顧名思義模板驗證就是通過一些angularjs的屬性來在html標籤中驗證,爲了往模板驅動表單中添加驗證機制,你要添加一些驗證屬性,就像原生的 HTML 表單驗證器。 Angular 會用指令來匹配這些具有驗證功能的指令。每當表單控件中的值發生變化時,Angular 就會進行驗證,並生成一個驗證錯誤的列表(對應着 INVALID 狀態)或者 null(對應着 VALID 狀態)。
2示例
這是我寫的一個小demo,這種驗證方式無需寫js代碼全部在標籤 裏使用angularjs的屬性,其他地方也無需引入angular forms庫,因爲ionic會自動默認引入。
<header [title]="title"></header>
<ion-content scroll="false">
<!--<form>-->
<ion-item>
<ion-input type="text" class="form-control"
name="username" #username="ngModel"
required maxlength="10" minlength="6"
placeholder="用戶名"
[(ngModel)]="user.username"
></ion-input>
</ion-item>
<p>ahdasidhasidashdudi</p>
<ion-item>
<ion-input type="password" class="form-control"
name="password" #password="ngModel"
required maxlength="16" minlength="6"
placeholder="密碼" [(ngModel)]="user.password"></ion-input>
</ion-item>
<ion-item>
<ion-label>記住密碼</ion-label>
<ion-toggle [(ngModel)]="pepperoni"></ion-toggle>
</ion-item>
<button ion-button block (click)="login()">登錄</button>
<ion-item>
<button ion-button icon-start outline (click)="goRegistered()">
去註冊
</button>
<button ion-button icon-end outline>
忘記密碼
</button>
</ion-item>
<h1 class="errorMessage">{{promptMessage}}</h1>
<span *ngIf="username.invalid && (username.dirty || username.touched)"
class="errorMessage">用戶名必須爲6到10位</span>
<span *ngIf="password.invalid && (password.dirty || password.touched)" class="errorMessage">
密碼必須爲6-16位
</span>
<!--</form>-->
</ion-content>
運行效果如下:
3核心屬性
可以看到[(ngModel)]="user.username"作用是綁定了我們在ts文件中定義的變量。
#username="ngModel"的作用是把我們綁定的模型值命名成username,變成了一個FormControl對象,這裏不必糾結下節會講。
required 驗證是否爲空 maxlength="10" 最大長度 minlength="6"最小長度。這些都是我們需要驗證的條件。
*ngIf="username.invalid && (username.dirty || username.touched)"
*ngIf標籤等於true時將錯誤信息顯示出來username.invalid表示驗證不合法返回true,username.dirty 判斷是否改變了這個參數的值,username.touched表示是否有碰過表單,作用在於,剛打開表單頁面是,裏面參數都是空的,但無需顯示錯誤信息。
進入model.d.ts文件看到部分源碼如下
/**
* A control is `valid` when its `status === VALID`.
*
* In order to have this status, the control must have passed all its
* validation checks.
*/
readonly valid: boolean;
/**
* A control is `invalid` when its `status === INVALID`.
*
* In order to have this status, the control must have failed
* at least one of its validation checks.
*/
readonly invalid: boolean;
valid屬性表示參數值校驗後結果不通過爲false,通過爲true。
invalid則表示參數值校驗不通過爲true,通過爲false。
/**
* A control is `dirty` if the user has changed the value
* in the UI.
*
* Note that programmatic changes to a control's value will
* *not* mark it dirty.
*/
readonly dirty: boolean;
/**
* A control is marked `touched` once the user has triggered
* a `blur` event on it.
*/
readonly touched: boolean;
dirty表示你是否沒有改變過這個參數的值