[Angular] 驗證密碼一致性 directive

Angular 驗證密碼一致性

password check directive in angularjs

// directives.js
'use strict'

angular.module('fooApp')
    .directive('passMatch', function () {
        return {
            // restrict: 'A', // only activate on element attribute
            require: 'ngModel', // get a hold of NgModelController
            link: function (scope, elem, attrs, model) {
                if (!attrs.passMatch) {
                    console.error('passMatch expects a model as an argument!');
                    return;
                }
                scope.$watch(attrs.passMatch, function (value) {
                    // Only compare values if the second ctrl has a value.
                    if (model.$viewValue !== undefined && model.$viewValue !== '') {
                        model.$setValidity('passMatch', value === model.$viewValue);
                    }
                });
                model.$parsers.push(function (value) {
                    // Mute the nxEqual error if the second ctrl is empty.
                    if (value === undefined || value === '') {
                        model.$setValidity('passMatch', true);
                        return value;
                    }
                    var isValid = value === scope.$eval(attrs.passMatch);
                    model.$setValidity('passMatch', isValid);
                    return isValid ? value : undefined;
                });
            }
        }
    });
<form name="form">
    <input type="password" ng-model="login.password">
    <input type="password" ng-model="login.verify" nx-equal-ex="login.password" name="verify">
    <span ng-show="form.verify.$error.nxEqualEx">Must be equal!</span>
</form>

參考連接

Directive Resources

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容