Securing data with ngModel encryption in AngularJS

Is it possible to encrypt only the $modelValue of a ngModel using any algorithm, while keeping the view value in plain text?

I attempted to create a custom directive to achieve this:

angular.module('utilityModule').directive('encrypt', function() {
    var aesUtil = new AesUtil(128, 10);
    return {
        restrict: 'A',
        require: 'ngModel',
        replace: false,
        compile: function(tElem, tAttrs) {
            var modelName = tAttrs['ngModel'];
            var pattern = tAttrs['ngPattern']; // to check if there is ngPattern directive used.
            return {
                pre: function(scope, element, attrs, fn) {
                    // to avoid encrypting on every key press.
                    fn.$options = {
                        updateOn: 'blur'
                    };
                    fn.$parsers.push(function(value) {
                        //encrypt
                        console.log('parser invoked');
                        return value ? aesUtil.encrypt(modelName, modelName, modelName, value) : value;
                    });
                    fn.$formatters.push(function(value) {
                        //decrypt
                        console.log('formatter invoked');
                        return value ? aesUtil.decrypt(modelName, modelName, modelName, value) : value;
                    });
                    fn.$validators.pattern = function(){
                        // trying to overrule ngPattern directive. DOESN'T HELP!!
                        return true;
                    };
                    // Just for playing around
                    fn.$validators.amyValid = function(modelValue, viewValue) {
                        console.log('Custom validator invoked. modelValue=' + modelValue + ' and viewValue=' + viewValue);
                        return true;
                    };
                },
                post: function(scope, element, attrs, fn) {}
            };
        }
    };
});

The custom directive works well, except when the ngPattern directive is used alongside ngModel. For instance:

<div class="table-responsive" ng-form="testForm">
        <input name="test" type="text" ng-model="test" encrypt ng-pattern="/^[0-9]+$/"/>
        <br>
        {{test}}
    </div>

What I'm looking for:

The ngPattern directive should validate using the $viewValue rather than the $modelValue.

Is there a way to override the 'patternDirective' directive in the core angular.js file?

Any other suggestions would also be appreciated...

UPDATE 1

I've noticed that not only ngPattern, but also other validations like maxLength, minLength, max, min should be applied to the view value only.

UPDATE 2

My debugger indicates that the value passed to the patternDirective validator is the encrypted one. Please refer to the screenshot attached.https://i.sstatic.net/9E2px.png

UPDATE 3

Updating to angularjs 1.4.5 resolved the issue. It seems that in version 1.3.x, validation is done on the model value rather than the view value.

Answer №1

After updating to angularjs version 1.4.5, the issue was resolved. It seems that the validation in 1.3.x is based on the model value rather than the view value.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How come my $scope variables are not resetting when attempting to refresh the data?

I just started working with Angular and encountered an issue while trying to implement a reload button. My webpage displays a table with data pulled from a Parse database. The table can be modified using various buttons, and after making changes, I want to ...

Page Not Found: React and Express Route Not Found

I encountered an error while attempting to use the sign-up route: POST http://localhost:3001/sign-up 404 (Not Found). I searched for similar issues on StackOverflow but couldn't pinpoint the source of my problem... In the frontend, I am fetching the ...

problem when trying to establish the minimum height for a div element prior to the website being fully loaded, considering the

Having trouble with a CSS issue that seems simple but I can't find a solution for. I have a main div with a min-height set to a certain value, specified in %. Since there is no outer div, the min-height won't display if it's given in px. I ...

Fetching data using an Ajax request in PHP is encountering issues, whereas the same request is successfully

I am experiencing an issue with a simple Ajax call in ASP.NET that works fine, but encounters a strange DOM Exception when I insert a breakpoint inside the onreadystatechange function. Can anyone explain why ASP.NET seems to have some additional header log ...

Receiving a Javascript Callback from Paypal

Is it possible to receive a JavaScript callback after a successful PayPal purchase made using a button? I am aware of IPN, but it requires a return URL. My main goal is to simply determine if a user has completed a purchase with the button. ...

JavaScript causing values to disappear when the page refreshes

When a user hovers over ImageButtons, I use Javascript to change the ImageUrl. However, on submitting the form, the updated ImageUrl property is not reflected in the code behind. Similarly, I also dynamically update a span tag using Javascript, but its alt ...

Change the dropdown header behavior from hovering over it to clicking on it

This snippet of code is integrated into our header to showcase the cart. Currently, the dropdown appears when hovering over it. Is there a way to adjust this so that the dropdown shows up when onclick? <a href="#header-cart" class="skip-link skip-cart ...

Transferring information among PHP web pages using a list generated on-the-fly

I am working with a PHP code that dynamically generates a list within a form using data from a database: echo '<form name="List" action="checkList.php" method="post">'; while($rows=mysqli_fetch_array($sql)) { echo "<input type='pas ...

What is the best way to target changing elements displayed by *ngIf?

Trying to access a dynamic element generated by ngIf in the code below has proven to be challenging. I attempted two different methods: Using ElementRef and querySelector Component template: `<div class="test" *ngIf="expr"> <a id="b ...

The provider named toasterProvider is not recognized within the dependency injection chain, which includes toaster, RugHttpInterceptor, $http, and ng1UIRouter

Working with Interceptors to show a toast message when my app encounters an HTTP error in responseError code. Using AngularJS Interceptor for an MEAN.JS app. Interceptor Code angular.module('rugCoPro') .factory('RugHttpInterceptor', ...

Develop a Vue mixin to enable theme switching in a Vue.js application

I have successfully developed three distinct themes: light, default, and dark. Currently, I am working on implementing a toggle function in the footer section that allows users to switch between these themes effortlessly. Following the guidance provided b ...

Utilize SVGs efficiently by loading them once and reusing them

Is it possible to use the same SVG element twice on a web page without having to load it again? I am changing the CSS of the SVG using JavaScript, so I believe the SVG must be directly embedded in the HTML rather than included as an object. Both instance ...

Utilizing namespacing in a JavaScript library can enhance organization and flexibility, providing

Creating a JavaScript library with multiple modules is my next project. Imagine the library is named Library, with modules One and Two. My goal is to allow end users to call the library in two ways: Library.One.somefunction(params) or somefunction(param ...

Leverage Redis to facilitate memory sharing among node.js instances in RxJS

We are currently developing a project that involves creating an event processor using RxJS. The system relies on specific rules where input is collected from various sources and output is generated based on the frequency of inputs exceeding a certain thres ...

ngAnimate - Animation not activating on recurring custom directive

I am trying to implement ngAnimate on a custom directive that is repeated using ng-repeat in my AngularJS application. The animations function correctly when I use ng-repeat on a simple HTML list-item. However, when I replace the list-item with a custom di ...

Using the ng-if directive in Angular to display a different class

In attempting to display a table with true and false values for each data retrieved from an API, I encountered an issue. If the value is true, the corresponding <td> should contain: <td><span class="label label-success status-active" title= ...

Creating a JSON object from text using JavaScript is a straightforward process

Looking to generate an object using the provided variable string. var text ='{"Origin":"Hybris","country":"Germany","Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

The Bootstrap modal window refuses to shut down

In my React application, I am utilizing Bootstrap modal functionality. One specific requirement is that the modal window should remain open when clicking on the modal backdrop. To achieve this, I have implemented the following code: $(".modal").modal({"ba ...

Using jQuery to encapsulate HTML within a div tag

I am looking to insert some HTML markup into my webpage using jQuery. I want to wrap the highlighted yellow code below with <div class="section">...</div>. Here is an example of what I need: <div class="section"> <div>...< ...

The ng-repeat feature is causing duplicate models to be held when dynamically adding items

I am currently developing a webpage that allows users to dynamically add line items. The framework I am using is AngularJS (v 1.4.7). While I was successful in adding items dynamically to the ng-repeat, I encountered an issue where the modal did not appear ...