angular學習筆記(二十)-表單驗證

本篇主要介紹angular中的表單驗證:css

表單驗證主要有如下一些內容:html

1. required指令: 至關於html5的required屬性,驗證不能爲空html5

2. ng-maxlength屬性: 驗證內容的長度最大值git

3. ng-minlength屬性: 驗證內容的長度最小值github

4. 表單名.$valid : 這個屬性用來獲取表單驗證的狀態,若是全部的驗證都經過了,它就是true,只要有一項不經過,它就是false數據庫

5. ng-disabled屬性: 判斷按鈕是否禁用. 值爲true時,禁用該按鈕瀏覽器

6. type屬性: type="email" , type="number" ,雖然這些都是html5的屬性,可是在angular中用法一致,能夠兼容不支持html5的瀏覽器,實現相同的功能app

下面來看一個簡單的表單驗證的例子:ui

 

在尚未填寫任何信息的時候,提交按鈕是禁用的,spa

暱稱不能爲空 \ 郵箱須要符合郵箱相關格式 \ 年齡在1-3位數之間數字

所有經過驗證後,提交按鈕不由用.

提交成功後,顯示成功提示

 

代碼以下:

<!DOCTYPE html>
<html ng-app="FormValidation" id="ng-app">
<head>
  <title>17.1表單驗證</title>
  <meta charset="utf-8">
  <script src="../angular.js"></script>
  <script src="script.js"></script>
  <style type="text/css">
    *{
      font-family:'MICROSOFT YAHEI';
      font-size:12px
    }
    h3 {
      color:#CB2027
    }
  </style>
</head>
<body>
<div>
  <form name="signUp" ng-controller="myform">
    <h1>註冊:</h1>
    <h3 ng-show="message">{{message}}</h3>
    <span>暱稱:</span><span><input type="text" ng-model="user.name" required/></span>
    <br>
    <span>郵箱:</span><span><input type="email" ng-model="user.email" required/></span>
    <br>
    <span>年齡:</span><span><input type="number" ng-model="user.age" required ng-maxlength="3" ng-minlength="1"/></span>
    <br>
    <button ng-disabled="!signUp.$valid" ng-click="addUser()">提交</button>
  </form>
</div>
</body>
</html>
var formValidation = angular.module('FormValidation',[]);
formValidation.controller('myform',function($scope){
    $scope.user = {
        name:'',
        email:'',
        age:''
    };
    $scope.message = "";
    $scope.addUser = function(){
        //把數據存入數據庫   
$scope.message
= "提交成功,歡迎您,"+$scope.user.name; } });

下面講解一下這段代碼:

 

①<form name="signUp" ng-controller="myform">

 <button ng-disabled="!signUp.$valid" ng-click="addUser()">提交</button> 

表單須要有一個名字,signUp.$valid就是這個表單的驗證狀態,這個狀態決定了button按鈕是否禁用.

當全部的驗證都經過時,signUp.$valid值就是true,不然,就是false

 

②<button ng-disabled="!signUp.$valid" ng-click="addUser()">提交</button>

ng-disabled屬性用於綁定元素是否禁用,若是是true就禁用, false則不由用.

 

③required

   添加該指令的元素,表示須要被驗證.

<input type="text" ng-model="user.name" required/>
普通的text文本input,只驗證是否爲空
<input type="email" ng-model="user.email" required/>
type爲'email'的input,驗證是否爲郵箱格式
<input type="number" ng-model="user.age" required ng-maxlength="3" ng-minlength="1"/>
type爲'number'的input,驗證是否爲數字

④<input type="number" ng-model="user.age" required ng-maxlength="3" ng-minlength="1"/>

   ng-maxlength 和 ng-minlength 屬性,驗證內容的長度

 

<h3 ng-show="message">{{message}}</h3>

   ng-show的值,不必定要是true或者false,這裏的message爲空的時候,就會是false,有值的話就是true.

   因此,當message不爲空的時候,h3就會被顯示出來

 

打開時的頁面:

當所有正確填寫後,按鈕再也不被禁用:

點擊提交後顯示成功提示:

 

完整代碼: https://github.com/OOP-Code-Bunny/angular/blob/master/OREILLY/17.1.%E8%A1%A8%E5%8D%95%E9%AA%8C%E8%AF%81.html

             https://github.com/OOP-Code-Bunny/angular/blob/master/OREILLY/script.js

相關文章
相關標籤/搜索