角度指令验证和解密

时间:2015-02-27 15:03:24

标签: javascript angularjs angularjs-directive cryptojs

我正在尝试构建一个首先验证用户输入的指令。

在验证输入后,我想用sha256散列字符串并返回一个只包含加密输入的新模型。

我知道这是一个奇怪的功能,但我有一个客户需要这样:)

以下是我的地址: Plunkr

var app = angular.module("myApp", []);

app.directive('ccInput', function () {

    var types = {
        'socialSecurityNumber': {
            'regex': /^[0-9]{6}-[0-9pPtTfF][0-9]{3}$/,
            'type': 'text',
            'error': 'The value you entered is not a valid social security number.'
        }
    };

    //CryptoJS.SHA256("hejsan Stefan hur måpr du");

    var getType = function (type) {
        return types[type];
    };

    return {
        restrict: 'E',
        require: 'ngModel',
        replace: true,
        scope: {
            ccType: "@",
            ccId: "@",
            ccLabel: "@",
            ccModel: "=ngModel"
        },
        template: '<div class="cc-group"><label class="cc-form-label" for="{{ccId}}">{{ccLabel}}</label><input id="{{ccId}}" class="cc-form-input" data-ng-model="ccModel" type="{{inputType}}" ng-pattern="inputRegex" /></div>',
        link: function (scope, elm, attr, ctrl) {


            var options = {},
                textField = angular.element(elm[0].lastChild),
                parser,
                formatter;
            if (!ctrl) {
                return;
            }


            options = getType(attr.ccType);
            scope.inputType = options.type;
            scope.inputRegex = options.regex;
        }
    };
});

1 个答案:

答案 0 :(得分:0)

通过简化脚本解决了我的问题。

app.directive('valiCrypt', function ($timeout) {

    var validateInput =function(input) {
         // Returns validation logic result here.
    }

    return {
        restrict: 'A',
        require: 'ngModel',
        replace: true,
        scope: {
            vcModel: "=ngModel",
            vcDuration: "@",
            vcText: "@"
        },

        link: function (scope) {

            if (!scope.vcDuration) {
                scope.vcDuration = 0;
            }

            if (!scope.vcText) {
                scope.vcText = "";
            }

            scope.$watch('vcModel', function (value) {
                if (value) {
                    if (value.length === 11) {
                        var result = validateInput(value);

                        if (result) {

                            var copy = angular.copy(scope.vcModel);

                            scope.vcModel = scope.vcText;

                            $timeout(function () {
                                // <script src="http://crypto-js.googlecode.com/svn/tags/3.1.2/build/rollups/sha256.js"></script>
                                copy = CryptoJS.SHA256(value);
                                scope.vcModel = copy;
                            }, scope.vcDuration, true);
                        }
                    }
                }
            });
        }
    };
});