美文网首页我爱编程
[Angular] 验证密码一致性 directive

[Angular] 验证密码一致性 directive

作者: kimoCHG | 来源:发表于2017-01-07 16:57 被阅读0次

    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

    相关文章

      网友评论

        本文标题:[Angular] 验证密码一致性 directive

        本文链接:https://www.haomeiwen.com/subject/stpfbttx.html