Issue with directive implementation of regex test as attribute - validations in typescript and angular

I am currently working on a project to create a module with custom validation directives.

These validations are implemented using regular expressions (regex).

The specific error I encountered is:

Error: [$injector:unpr] Unknown provider: REG_EXPProvider <- REG_EXP <- uniIdValidatorDirective

Here is an overview of my code:

config.ts:

module LoginModule {

    'use strict';

    /***** REGEX *****/
    export class regExp {
        public ID_OR_PASSPORT = /^[0-9]{9}$/;
        public USERNAME_SINGLE_WORD = /^[A-Za-z0-9à-ú-_\.]{6,8}$/;
        public PASSWORD = /^[A-Za-z0-9à-ú-_\.]{8}$/;
        public EMAIL = /^([\?!\/]*)+\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        public ALPHANUMERIC = /^[a-zA-Z0-9]+$/;
        public NUM = /^[0-9]{1,}[.]{0,1}[0-9]{0,}$/;
        public PHONE_BODY = /^[0-9]{7}$/;
    };
    angular.module("LoginModule").value('REG_EXP', regExp);
}

Validation directive:

module LoginModule {
    uniIdValidator.$inject = ['REG_EXP'];
    angular.module('LoginModule').directive('uniIdValidator', uniIdValidator);
    export function uniIdValidator(REG_EXP): ng.IDirective {
        return {
            restrict: 'A',
            require: ['ngModel'],
            templateUrl: 'errorMessages.html',
            replace: true,
            link: (scope: ng.IScope, element: ng.IAugmentedJQuery, 
                   attrs: ng.IAttributes, ctrls:any) => {
                ctrls.$validators.userId = function (modelValue) {
                    return REG_EXP.ID_OR_PASSPORT.test(modelValue);
                };
            }
        }
    };
}

In the HTML file:

<Input ... uni-id-validator />

Added in app.ts:

((): void=> {
    var appLogin = angular.module("LoginModule", ['ngRoute', 'ngMessages']);
    appLogin.config(LoginModule.Routes.configureRoutes);
})() 

Answer №1

Here is a demonstration of a functional plunker example that showcases the effectiveness of the approach below in creating a directive simplified REG_EXP implementation)

The method I employ to develop directives using Typescript bears similarity to this:

module LoginModule {
    //uniIdValidator.$inject = ['REG_EXP'];
    //angular.module('LoginModule').directive('uniIdValidator', uniIdValidator);
    export class uniIdValidator implements ng.IDirective 
    {
        constructor(public REG_EXP) {}
        public restrict: string = 'A';
        public require: string = 'ngModel';
        public templateUrl: string = 'errorMessages.html';
        public replace: boolean = true;
        public link: Function = (scope: ng.IScope, 
            element: ng.IAugmentedJQuery,
            attrs: ng.IAttributes, 
            ctrls:any) => 
            {
                ctrls.$validators.userId = function (modelValue) 
                {
                    //return REG_EXP.ID_OR_PASSPORT.test(modelValue);
                    return "TO DO";
                };
            }          
    }

    angular.module('LoginModule')
      .directive('uniIdValidator', ['REG_EXP', 
          (REG_EXP) =>  {return new LoginModule.uniIdValidator(REG_EXP) });
}

Explore it further here. If you're interested in converting TS to JS, refer to

There is a working plunker (showing that the below approach is able to create working directive with simplified REG_EXP implementation)

The way I do create directives with Typescript is similar to this:

module LoginModule {
    //uniIdValidator.$inject = ['REG_EXP'];
    //angular.module('LoginModule').directive('uniIdValidator', uniIdValidator);
    export class uniIdValidator implements ng.IDirective 
    {
        constructor(public REG_EXP) {}
        public restrict: string = 'A';
        public require: string = 'ngModel';
        public templateUrl: string = 'errorMessages.html';
        public replace: boolean = true;
        public link: Function = (scope: ng.IScope, 
            element: ng.IAugmentedJQuery,
            attrs: ng.IAttributes, 
            ctrls:any) => 
            {
                ctrls.$validators.userId = function (modelValue) 
                {
                    //return REG_EXP.ID_OR_PASSPORT.test(modelValue);
                    return "TO DO";
                };
            }          
    }

    angular.module('LoginModule')
      .directive('uniIdValidator', ['REG_EXP', 
          (REG_EXP) =>  {return new LoginModule.uniIdValidator(REG_EXP) });
}

Check it here. Here is a link to place which was used to transpile the TS to JS.

Some other link to Q & A (or here) with working examples...

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

Is it accurate to categorize every ajax request (using xmlhttprequest) as a web service request?

Recently, I began incorporating AngularJS with Spring MVC as my backend. I have been utilizing $resource to connect with my backend. Given that this is a restful service and $resource operates using ajax, I find myself questioning: 1) Is ajax solely used ...

What are some recommended methods in Angular for developing reusable panels with both controller and view templates?

I am still getting acquainted with angularjs, so there might be something I'm overlooking, but I'm struggling to find an efficient way to create reusable views that can be instantiated within a parent view. My specific scenario involves a web ap ...

What is causing my function to execute twice in all of my components?

One issue I am facing is that I have created three different components with routing. However, when I open these components, they seem to loop twice every time. What could be causing this behavior and how can I resolve it? For instance, in one of the comp ...

Using AngularJS to pass the output of a unique filter to another custom filter

I have successfully developed two custom filters and am attempting to utilize them both within an ng-repeat loop. Is there a way for me to pass the output of the first filter as an input for the second one? I attempted using 'as' keyword in ng- ...

Having trouble extracting parameters with TypeScript in React Router even when they are present

I am in the process of migrating an older project to utilize react and react-router. Additionally, I am fairly new to typescript, which is the language used for this particular project. Any guidance or explanations on these topics would be highly beneficia ...

I used npm to install AngularJS and then included AngularJS in my application

My goal is to set up AngularJS v1.5.x using npm and integrate it into my application for seamless utilization. Most tutorials opt for downloading the Angular Version from angularjs.org and manually adding it to the index.html within a <script></sc ...

Implementing JSON object array retrieval from MySQL database and placing it into an empty array using AngularJS

Recently, I've been working on retrieving data from a MySQL database using PHP. Here is the snippet of code that I have written: $result = mysqli_query($con,"SELECT * FROM customers"); $return_arr = array(); while($row = $result->fetch_array(MYSQ ...

What is the reason behind the lack of access for modal to an external controller?

Imagine having this code in your main HTML file: <body ng-app="app" ng-controller="session as vmSession"> ... <!-- Modal content goes here --> </body> Inside the modal, you have a link: <a ui-sref="siteManagement({ site: vmSession.u ...

Angular 14: Deleting an item from a FormArray triggers unintended form submission due to Angular animation

After beginning to create animations for my app, I observed that deleting an element from a FormArray triggers a form submission. Custom form controls were developed using ControlValueAccessor, and certain FormGroups are passed through @Inputs. The animati ...

Generate tables and rows dynamically

I am looking for guidance on dynamically creating a table and adding rows to it. I have successfully created a table with one row containing form fields, but I am unsure how to add additional rows. Any examples or suggestions on how this can be implemented ...

What is the reason for the failure of <option selected="selected">?

Even though my ng-selected expression is supposed to set the selected="selected" attribute in the <option> tag (as shown in the screenshot http://prntscr.com/bmgozg), for some mysterious reason, this particular <option> element still remains un ...

Basic $http.get request including parameters

I've been attempting to send an HTTP request using the AngularJS $http service like this: $http.get('http://myserver:8080/login?', { params: {username: "John", password: "Doe" }, headers: {'Authorization': ...

Decrease initial loading time for Ionic 3

I have encountered an issue with my Ionic 3 Android application where the startup time is longer than desired, around 4-5 seconds. While this may not be excessive, some users have raised concerns about it. I am confident that there are ways to improve the ...

Exploring Methods for Retrieving offsetHeight and scrollHeight in AngularJS

I am currently developing a directive that requires three specific values: scrollTop offsetHeight scrollHeight projectModule.directive('scroller', function ($window) { return { restrict: 'A', link: function (scope, elem, attrs) { ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

How can I go about setting up $broadcast?

I've been utilizing the fantastic ngStorage plugin for Angular development. Setting up involves connecting a $scope-node to the localstorage in this manner: $scope.$store = $localStorage; The $scope.$store is now accessible across all controllers. ...

What is the best way to display audio files for clients using a combination of Node.js and AngularJS?

After successfully converting my wav files to mp3 files using the ffmpeg converter, I am able to upload them to a designated "uploads" folder. However, I am facing difficulty in displaying these files on the browser. My current setup involves utilizing An ...

Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data. data = ['middlename.firstname.lastname','firstname.lastname']; During the process, I am looping through the .html usin ...

Typescript error: Cannot assign type to argument

Exploring the world of typescript (2.5.2) and looking for clarity on why the first call works but the second one encounters an error: function printPerson(person: {firstName: string; lastName: string}): void{ console.log(person.firstName + " " + per ...

Issue with cordova plugin network interface connectivity

I'm currently working with Ionic 2 Recently downloaded the plugin from https://github.com/salbahra/cordova-plugin-networkinterface Attempting to retrieve IP addresses without utilizing global variables or calling other functions within the function ...