AngularJs功能(八)--表單驗證

表單驗證

表單驗證是angularJS一項重要的功能,能保證咱們的web應用不會被惡意或錯誤的輸入破壞。Angular表單驗證提供了不少表單驗證指令,而且能將html5表單驗證功能同他本身的驗證指令結合起來使用,進而在客戶端驗證時提供表單狀態的實時反饋。javascript

要使用表單驗證,首先保證表單有一個name屬性,通常的輸入字段如最大,最小長度等,這些功能由html5表單屬性提供,若是咱們想屏蔽瀏覽器對錶單的默認驗證行爲,能夠在表單元素上添加novalidate標記。html

實例

插入一段項目中註冊的表單實例html5

//HTML
<form name="loginForm" class="login-form" novalidate="novalidate">
<div class="form-title">
    用戶註冊
</div>
<div class="form-group" ng-class="{'has-error': (loginForm.loginId.$touched || loginForm.$submitted) && loginForm.loginId.$invalid}">
    <div class="input-icon">
        <!-- '^0{0,1}(13[0-9]|(14[5|7])|(15([0-3]|[5-9]))|17[0-9]|(18[0,5-9]))[0-9]{8}$' -->
        <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="手機號/郵箱" ng-pattern="/(^1[0-9]{10}$)|(^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$)/i" name="loginId" ng-model="model.loginId" required ng-maxlength="20"/>
    </div>
    <div class="help-block" ng-show="(loginForm.$submitted || loginForm.loginId.$touched)&& loginForm.loginId.$invalid" ng-messages="loginForm.loginId.$error">
        <div ng-message="required">
            手機號或郵箱不能爲空
        </div>
        <div ng-message="pattern">
            手機號或郵箱格式錯誤
        </div>
        <div ng-message="maxlength">
            手機號或郵箱長度不超過20位
        </div>
    </div>
</div>
<div class="form-group" ng-class="{'has-error': (loginForm.password.$touched || loginForm.$submitted) && loginForm.password.$invalid}">
    <div class="input-icon">
        <div class="input-group">
            <input class="form-control placeholder-no-fix" type="text" autocomplete="off" placeholder="請輸入驗證碼" name="password" ng-model="model.password" required ng-focus="hideErrorMsg()" ng-maxlength="20"/>
            <span class="input-group-addon active-btn" ng-if="!verificationCodeFlag" ng-click="getVerificationCode(loginForm)">獲取動態驗證碼</span>
            <span class="input-group-addon" ng-if="verificationCodeFlag" ng-bind="'從新獲取(' + second +')'" style="cursor:not-allowed;"></span>
        </div>
    </div>
    <div class="help-block" ng-show="(loginForm.$submitted || loginForm.password.$touched)&& loginForm.password.$invalid" ng-messages="loginForm.password.$error">
        <div ng-message="required">
            驗證碼不能爲空
        </div>
        <div ng-message="maxlength">
            驗證碼長度不超過20位
        </div>
    </div>
    <div class="help-block" ng-if="registerResultStatus">
        <!--ng-bind-html="errorMessage"-->
        <div style="color: #f96827;font-size: 12px;">
            {{errorMessage}}
            <a ng-if="showLoginLinkFlag" href="../loginFront/redirecting.html" style="text-decoration:underline;">登陸</a>
        </div>
    </div>
</div>
<div class="form-actions">
    <label class="checkbox">
    <input type="checkbox" id="agree" name="agree" ng-model="agree" ng-click="agreeOrCanel()"/>
    <label for="agree">我明白並贊成</label>
    <a class="terms" href="javascript:void(0);" ng-click="showProtocal()">《橙色雲設計服務條款》</a>
    </label>
    <button type="button" class="btn green-haze pull-right" ng-click="saveInfor(loginForm)" disabled id="registerCustom">
        註冊
    </button>
</div>
</form>

 //註冊 JS
 var registUrl = "/cds/w/user/register.do";
 $scope.saveInfor = function(form) {
     form.$submitted = true;
     if (!form.$valid) return;
     var param = {
         loginId: $scope.model.loginId,
         password: $scope.model.password
     };
     $resource(registUrl + '?' + $scope._urlParamEncode(param), null, {
         'registerUser': {
             method: 'POST'
         }
     }).registerUser(param).$promise.then(function(result) {
         if (result.status === 'success') {
             $window.location.href = "/cds/portal/index.html";
         } else {
             $scope.registerResultStatus = true;
             if (result.message && result.message.indexOf("已註冊") > 0) {
                 var htmlMsg = '您的郵箱|手機號已註冊,請直接';
                 //<a href="../loginFront/redirecting.html" style="text-decoration:underline;">登陸</a>
                 $scope.showLoginLinkFlag = true;
                 $scope.errorMessage = $sce.trustAsHtml(htmlMsg);
             } else {
                 $scope.errorMessage = result.message;
             }

         }
     });
 };


//登陸按鈕是否禁用(贊成條框)
 $scope.agreeOrCanel = function() {
     var checkedState = $('#agree').attr('checked'); //記錄當前選中狀態
     if (checkedState == 'checked') {
         $('#registerCustom').removeAttr('disabled');
     } else {
         $scope.agreeDisable = false;
         $('#registerCustom').attr('disabled', true);
     }
 }

代碼放上來了。能夠下大體看一下,發現和以前使用的有何不一樣之處。java

下面咱們列舉表單中input元素上用到的驗證選項,好比:
1.必填項,設置某個表單輸入是否已經填寫,只須要在輸入字段元素上添加require標記便可。web

<input type="text" required>

2.最小(大)長度,驗證表單輸入的文本長度是否大於某個最小值,可使用ng-minlength指令(ng-maxlength指令)正則表達式

<input type="text" ng-minlength="5" ng-maxlength>

3.模式匹配,使用ng-pattern來確保輸入匹配指定的正則表達式api

<input type="text"  ng-pattern="/^[a-zA-Z]$/">

4.電子郵件,只須要把input的類型設置爲email便可
數字,只須要將input的類型設置爲numberpromise

<input type="email" name="email" ng-model="user.email" >
<input type="number" name="age" ng-model="user.age">

在實例中,咱們用到的是收拾好和郵箱均可驗證登陸,因此在匹配上的正則作文章。以下瀏覽器

<input type="text" autocomplete="off" placeholder="手機號/郵箱" 
ng-pattern="/(^1[0-9]{10}$)|(^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$)/i">

5.一樣咱們也能夠根據自定義的屬性指令來定義一些校驗規則,這裏不作詳細介紹。上一段代碼吧。app

<input type="text" placeholder="username" name="usrename" ng-model="user.username" check-username="username">

app.directive('checkUsername', function($http) {
 return {
    link: function(scope, ele, attrs, c) {
        scope.$watch(attrs.ngModel, function(n) {
            if (!n) return;
            $http({
                method: 'POST',
                url: '/api/check/' + attrs.username,
                data: {
                    field: attrs.username,
                    value: scope.ngModel
                }
        }).success(function(data) {
                //code
            }).error(function(data) {
                //code
            })
        });
    }
}

});

驗證規則

因爲表單的屬性能夠在其$scope對象中訪問到,而咱們又能夠直接訪問到$scope,所以js能夠間接的訪問DOM的表單屬性,藉助這些屬性,咱們能夠對錶單作出實時響應。
這些屬性有:

1.未修改的表單,用來判斷用戶是否修改了表單,若是修改了則爲true,未修改則爲false。

loginForm.loginId.$pristine

2.修改過的表單,只要用戶修改過表單,不管輸入是否經過驗證,該值都將返回true

loginForm.loginId.$dirty

3.合法的表單,這個屬性是用來判斷表單的內容是否合法的,若是合法則該屬性的值爲true

loginForm.loginId.$valid

4.不合法的表單,這個屬性與上個屬性正好相反,若是不合法,則該屬性值爲true

loginForm.password.$invalid

5.錯誤,$error對象包含了當前表單的全部驗證內容,以及它們是否合法的信息,若是驗證失敗,該屬性值爲true,若是驗證成功,則該值爲false

loginForm.password.$error

6.表單的提交驗證。

loginForm.$submitted

給form加上name="loginForm"意味着表單的名稱是loginForm。如何使用loginForm,好比咱們驗證表單是否被修改過loginForm.$submitted;

loginForm是$scope中的一個屬性

ng-class根據註冊狀態和提交狀態獲取不一樣樣式。

<div class="form-group" ng-class="{'has-error':(loginForm.loginId.$touched || loginForm.$submitted) && loginForm.loginId.$invalid}">

驗證提示

這是在angular1.3版本以後對angular表單驗證的優化。它再也不須要一個詳細的表達式狀態建立元素顯示或隱藏。看看項目中的代碼。

<div class="help-block" ng-show="(loginForm.$submitted || loginForm.loginId.$touched)&& loginForm.loginId.$invalid" ng-messages="loginForm.loginId.$error">
    <div ng-message="required">
        手機號或郵箱不能爲空
    </div>
    <div ng-message="pattern">
        手機號或郵箱格式錯誤
    </div>
    <div ng-message="maxlength">
        手機號或郵箱長度不超過20位
    </div>
</div>

能夠看出,angular經過$error來監視模型的變化,由於$error中包含了錯誤的詳細信息,
用ng-message=""綁定驗證類型。會根據$error錯誤類型提示錯誤信息。
同時,若是咱們的應用場景中若是同時,有好幾處錯誤,那麼,上面代碼按照ng-message的順序只會顯示一條錯誤信息,若是咱們須要所有顯示出來只須要添加 ng-messages-multiple。

<div class="help-block" ng-messages="loginForm.loginId.$error" ng-messages-multiple>

這裏只作範例介紹,小夥伴們在項目中合理運用就好。

相關文章
相關標籤/搜索