溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

使用AngularJS怎么實(shí)現(xiàn)自定義表單驗(yàn)證功能

發(fā)布時(shí)間:2021-05-22 17:19:56 來(lái)源:億速云 閱讀:134 作者:Leah 欄目:web開發(fā)

這篇文章給大家介紹使用AngularJS怎么實(shí)現(xiàn)自定義表單驗(yàn)證功能,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

Angular實(shí)現(xiàn)了大部分常用的HTML5的表單控件的類型(text, number, url, email, date, radio, checkbox),也實(shí)現(xiàn)了很多指令做為驗(yàn)證(required, pattern, minlength, maxlength, min, max)。

在自定義的指令中,我們可以添加我們的驗(yàn)證方法到ngModelController的$validators對(duì)象上。為了取得這個(gè)controller對(duì)象,我們需要requirengModel指令。

在$validators對(duì)象上的每個(gè)方法都接收modelValue和viewValue兩個(gè)值做為參數(shù)。在你綁定的驗(yàn)證方法返回一個(gè)值(true,false)之后,Angular會(huì)在內(nèi)部調(diào)用$setValidity方法。驗(yàn)證會(huì)在每一次輸入框的值改變($setViewValue被調(diào)用)或者模型的值改變。驗(yàn)證發(fā)生在$parsers和$formatters成功運(yùn)行之后,驗(yàn)證不通過(guò)的項(xiàng)會(huì)做為ngModelController.$error的屬性存儲(chǔ)起來(lái)。

另外,在這個(gè)controller對(duì)象上,還有一個(gè)$asyncValidators對(duì)象,如果你的驗(yàn)證是異步的,則需要加驗(yàn)證附加在這個(gè)對(duì)象上,比如說(shuō)用戶注冊(cè)時(shí)輸入手機(jī)號(hào),我們需要在后端驗(yàn)證該手機(jī)號(hào)是否已經(jīng)注冊(cè),這個(gè)驗(yàn)證方法必須return一個(gè)promise對(duì)象,然后在驗(yàn)證通過(guò)時(shí)調(diào)用延遲對(duì)象的resolve,失敗時(shí)調(diào)用reject,還未完成的異步的驗(yàn)證存儲(chǔ)在ngModelController.$pending中。

例如(注意其中的user對(duì)象,只有驗(yàn)證通過(guò)了,才會(huì)將值綁定到模型上):

<form name="register_form" ng-submit="save()">
    <div class="form-group">
        <label for="phoneNumber">
            手機(jī)號(hào)(不能重復(fù)):
        </label>
        <input type="text" class="form-control" ng-model="user.phoneNumber" id="phoneNumber" name="phoneNumber" required phone>
    </div>
    <div class="form-group">
        <label for="username">
            用戶名(必須大于五位):
        </label>
        <input type="text" class="form-control" ng-model="user.username" id="username" required username>
    </div>
    <button class="btn btn-block btn-primary" type="submit">提交</button>
</form>
<h4>用戶對(duì)象</h4>
<pre>
    {{ user | json }}
</pre>
'use strict';
angular.module('app', [])
.directive('phone', function ($q, $http) {
  return {
    require: 'ngModel',
    link: function (scope, ele, attrs, ctrl) {
      ctrl.$asyncValidators.phone = function (modelValue, viewValue) {
        var d = $q.defer();
        $http.get('phone.json')
        .success(function (phoneList) {
          if (phoneList.indexOf(parseInt(modelValue)) >= 0) {
            d.reject();
          } else {
            d.resolve();
          }
        });
        return d.promise;
      }
    }
  }
})
.directive('username', function ($q, $http) {
  return {
    require: 'ngModel',
    link: function (scope, ele, attrs, ctrl) {
      ctrl.$validators.username = function (modelValue, viewValue) {
        if (modelValue) {
          return modelValue.length > 5 ? true : false;
        };
        return false;
      }
    }
  }
})

phone.json

[
  13758262732,
  15658898520,
  13628389818,
  18976176895,
  13518077986
]

效果

使用AngularJS怎么實(shí)現(xiàn)自定義表單驗(yàn)證功能

下面一個(gè)完整的用戶注冊(cè)的表單驗(yàn)證:

html:

<form name="register_form" novalidate>
    <div class="form-group">
        <label for="username">用戶名:</label>
        <!-- ng-pattern="/PATTERN/"確保輸入項(xiàng)符合正則 -->
        <input type="text" id="username" ng-model="user.username" class="form-control" name="username" required ng-pattern="/^[^#]*$/">
        <span class="glyphicon glyphicon-ok right" ng-show="register_form.username.$valid"></span>
    </div>
    <div class="alert alert-danger" ng-show="register_form.username.$error.pattern">
        <strong>請(qǐng)注意!</strong>
        用戶名不能帶#號(hào)。
    </div>
    <div class="alert alert-danger" ng-show="register_form.username.$error.required && register_form.username.$touched">
        <strong>請(qǐng)注意!</strong>
        用戶名不能為空。
    </div>
    <div class="form-group">
        <label for="_password">密碼:</label>
        <!-- ng-minlength="num"讓密碼不能小于最小長(zhǎng)度 -->
        <input type="password" id="_password" ng-model="data._password" class="form-control" required ng-minlength="8" name="_password">
        <span class="glyphicon glyphicon-ok right" ng-show="register_form._password.$valid"></span>
    </div>
    <div class="alert alert-danger" ng-show="register_form._password.$error.minlength && register_form._password.$touched">
        <strong>請(qǐng)注意!</strong>
        密碼長(zhǎng)度不能少于八位。
    </div>
    <div class="alert alert-danger" ng-show="register_form._password.$error.required && register_form._password.$touched">
        <strong>請(qǐng)注意!</strong>
        密碼不能為空。
    </div>
    <div class="form-group">
        <label for="password">確認(rèn)密碼:</label>
        <input type="password" id="password" ng-model="user.password" class="form-control" name="password" required pwd-repeat>
        <span class="glyphicon glyphicon-ok right" ng-show="register_form.password.$valid"></span>
    </div>
    <div class="alert alert-danger" ng-show="register_form.password.$error.pwdRepeat && register_form.password.$touched">
        <strong>請(qǐng)注意!</strong>
        兩次輸入的密碼不相同。
    </div>
    <div class="alert alert-danger" ng-show="register_form.password.$error.required && register_form.password.$touched">
        <strong>請(qǐng)注意!</strong>
        請(qǐng)?jiān)俅屋斎朊艽a。
    </div>
    <div class="form-group">
        <label for="phone">手機(jī)號(hào):</label>
        <div class="row">
            <div class="col-sm-10">
                <input type="num" id="phone" ng-model="user.phone" name="phone" class="form-control" required ng-minlength="11" ng-maxlength="11" phone>
            </div>
            <div class="col-sm-2">
                <button class="btn btn-default" type="button" ng-disabled="register_form.phone.$invalid">發(fā)送驗(yàn)證碼</button>
            </div>
        </div>
        <span class="glyphicon glyphicon-ok right" ng-show="register_form.phone.$valid"></span>
    </div>
    <div class="alert alert-danger" ng-show="register_form.phone.$error.phone">
        <strong>請(qǐng)注意!</strong>
        該手機(jī)號(hào)已注冊(cè)過(guò),可直接登錄。
    </div>
    <div class="alert alert-danger" ng-show="register_form.phone.$touched && !register_form.phone.$error.phone && (register_form.phone.$error.required || register_form.phone.$error.minlength || register_form.phone.$error.maxlength)">
        <strong>請(qǐng)注意!</strong>
        請(qǐng)輸入正確的手機(jī)號(hào)。
    </div>
    <div class="form-group">
        <label for="code">驗(yàn)證碼:</label>
        <input type="text" id="code" ng-model="user.code" class="form-control" name="code" required>
        <span class="glyphicon glyphicon-ok right" ng-show="register_form.code.$valid"></span>
    </div>
    <!-- 在表單不合法時(shí)禁用提交按鈕 -->
    <button class="btn btn-block btn-primary" type="submit" ng-disabled="register_form.$invalid" ng-click="save()">提交</button>
</form>

js:

'use strict';
angular.module('app', [])
.controller('myCtrl', function ($scope) {
  $scope.data = {};
  $scope.save = function () {
    alert('保存成功!')
  }
})
// 判斷手機(jī)號(hào)是否重復(fù)
.directive('phone', function ($q, $http) {
  return {
    require: 'ngModel',
    link: function (scope, ele, attrs, ctrl) {
      ctrl.$asyncValidators.phone = function (modelValue, viewValue) {
        var d = $q.defer();
        $http.get('phone.json')
        .success(function (phoneList) {
          if (phoneList.indexOf(parseInt(modelValue)) >= 0) {
            d.reject();
          } else {
            d.resolve();
          }
        });
        return d.promise;
      }
    }
  }
})
// 驗(yàn)證兩次輸入的密碼是否相同的自定義驗(yàn)證
.directive('pwdRepeat', function () {
  return {
    require: 'ngModel',
    link: function (scope, ele, attrs, ctrl) {
      ctrl.$validators.pwdRepeat = function (modelValue) {
        // 當(dāng)值為空時(shí),通過(guò)驗(yàn)證,因?yàn)橛衦equired
        if (ctrl.$isEmpty(modelValue)) {
          return true;
        }
        return modelValue === scope.data._password ? true : false;
      }
    }
  }
})

css:

.form-group {
  position: relative;
}
.right {
  position: absolute;
  right: 10px;
  top: 34px;
  color: green;
}

phone.json:

[
  13758262732,
  15658898520,
  13628389818,
  18976176895,
  13518077986
]

關(guān)于使用AngularJS怎么實(shí)現(xiàn)自定義表單驗(yàn)證功能就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI