- <form name="form" novalidate>帳號:
- <input type="text" name="user" ng-model="username" required />
- <span ng-show="form.user.$error.required">帳號不得為空</span>
- <input ng-disabled="form.user.$dirty && form.user.$invalid" type="submit" />
- </form>
- 第1行:由於驗證結果(例如格式錯誤、未填寫等)必須透過表單存取,故必須設定name屬性,此處自訂表單的名稱為"form",供後續存取驗證結果。另外novalidate表示關閉browser內定的驗證機制,由AngularJS進行驗證。
- 第2行:每個要做輸入驗證的欄位,都必須自訂name屬性值,此處自訂為"user",如為必要欄位,則必須設定required。
- 第3行:驗證錯誤訊息。form.user代表第2行帳號填寫欄位。$error則是驗證結果出現錯誤。AngularJS內建了一些驗證程序,例如.requried會負責驗證有無填寫,因此使用$error.required代表未填寫。
下圖是加入驗證碼的三個欄位表單:
![]() |
圖1. 三個欄位都加入驗證功能 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<body ng-app="starter" > | |
<ion-header-bar class="bar bar-positive"text-align="center"> | |
<h1 class="title" >表單驗證</h1> | |
</ion-header-bar> | |
<ion-content ng-controller="formCtrl"> | |
<form name="myForm" novalidate> | |
<label class="item item-input-inset"> | |
<span class="input-label">帳號</span> | |
<input type="text" ng-model="username" name="user" required> | |
<span class="item-note" ng-show="myForm.user.$error.required">帳號不得為空</span> | |
</label> | |
<label class="item item-input-inset"> | |
<span class="input-label">Email</span> | |
<input type="email" ng-model="email" name="email" required> | |
<span class="item-note" ng-show="myForm.email.$error.required">Email不得為空</span> | |
<span class="item-note" ng-show="myForm.email.$error.email">Email格式錯誤</span> | |
</label> | |
<label class="item item-input-inset"> | |
<span class="input-label">密碼</span> | |
<input type="password" ng-model="password" name="passwd" required> | |
<span class="item-note" ng-show="myForm.passwd.$error.required">密碼不得為空</span> | |
</label> | |
<button class="button button-outline button-block" | |
ng-disabled= | |
"myForm.user.$dirty && myForm.user.$invalid | |
|| myForm.email.$dirty && myForm.email.$invalid | |
|| myForm.passwd.$dirty && myForm.passwd.$invalid" | |
>送出</button> | |
</form> | |
</ion-content> | |
</body> |
- 第6行:設定表單name屬性值為'myForm',並設定novalidate。
- 第9行:帳號欄位,須設定ng-model,name,且為必填欄位,故設定required。
- 第10行:驗證錯誤訊息,此為未填資料的錯誤狀況($error.required)。ng-show會在錯誤狀況發生時,才顯示訊息。
- 第14行:email欄位,設定ng-model,name,且為必填欄位,故設定required。
- 第15-16行:email欄位驗證錯誤訊息。email有格式錯誤的可能性,故多一行$error.email。ng-show會在錯誤狀況發生時,才顯示訊息。
- 第20行:密碼欄位,設定ng-model,name,且為必填欄位,故設定required。
- 第21行:密碼欄位驗證錯誤訊息($error.required)。
- 第24-27行:ng-disabled設定按鈕失效的條件。此處用到三個欄位的驗證狀況$dirty與$invalid。$dirty代表使用者已經輸入資料,$invalid代表目前驗證狀況屬於錯誤狀態。
index.html僅設定幾個$scope資料模型變數,完整程式碼可參考Gist範例。
表單驗證常用的屬性值如下:
沒有留言:
張貼留言