Directive unable to recognize ng-pattern functionality

I am attempting to encapsulate an <input> within a directive in order to manage date validation, conversion from string to Date object, and keep the Date version in the original scope. The functionality seems to be working as intended. However, the ng-pattern attribute on the <input> element is not functioning properly. It does not invalidate the <input>, regardless of the input.

HTML

<pl-date date="date"></pl-date>

JS

.directive("plDate", function (dateFilter) {
  return {
    restrict: 'E',
    replace: true,
    template: '<input id="birthDateDir" name="birthDate" type="text" ng-pattern="{{getDatePattern()}}" ng-model="dateInput">',
    scope: {
        date: '='
    },
    link: function (scope) {
        scope.dateInput = dateFilter(scope.date, 'MM/dd/yyyy');

        scope.$watch('date', function (newVal) {
            if (newVal !== scope.tmp) {
                if (!newVal) {
                    scope.dateInput = null;
                } else {
                    scope.dateInput = dateFilter(scope.date, 'MM/dd/yyyy');
                }
            }
        });

        scope.getDatePattern = function () {
            var exp = '/';

            // Removed for brevity

            exp += '/';

            return exp;
        };

        scope.$watch('dateInput', function (newVal) {
            if (newVal !== null) {
                scope.date = new Date(newVal);
                scope.tmp = scope.date;
            }
        });
    }
};

Check out the JSFiddle for this code snippet here: https://jsfiddle.net/e5qu5rgy/1/

I would greatly appreciate any assistance with this issue!

Answer №1

It appears that resolving the issue may involve adjusting the link function within the directive to a controller function instead. See below for the updated code:

.directive("plDate", ['$scope', '$element', '$attrs', 'dateFilter', function ($scope, $element, $attrs, dateFilter) {
    return {
        restrict: 'E',
        replace: true,
        template: '<input id="birthDateDir" name="birthDate" class="formField" type="text" ng-pattern="{{getDatePattern()}}" ng-model="dateInput">',
        scope: {
            date: '='
        },
        controller: function () {
            $scope.dateInput = dateFilter($scope.date, 'MM/dd/yyyy');

            $scope.$watch('date', function (newVal) {
                if (newVal !== $scope.tmp) {
                    if (!newVal) {
                        $scope.dateInput = null;
                    } else if (newVal.toString() !== "Invalid Date") {
                        $scope.dateInput = dateFilter($scope.date, 'MM/dd/yyyy');
                    }
                }
            });

            $scope.getDatePattern = function() {
                var exp = '/';

                // Months with 31 days
                exp += '^(0?[13578]|1[02])[\/.](0?[1-9]|[12][0-9]|3[01])[\/.](18|19|20)[0-9]{2}$';

                //Months with 30 days
                exp += '|^(0?[469]|11)[\/.](0?[1-9]|[12][0-9]|30)[\/.](18|19|20)[0-9]{2}$';

                // February in a normal year
                exp += '|^(0?2)[\/.](0?[1-9]|1[0-9]|2[0-8])[\/.](18|19|20)[0-9]{2}$';

                // February in a leap year
                exp += '|^(0?2)[\/.]29[\/.](((18|19|20)(04|08|[2468][048]|[13579][26]))|2000)$';

                exp += '/';

                return exp;
            };

            $scope.$watch('dateInput', function (newVal) {
                if (newVal !== null) {
                    $scope.date = new Date(newVal);
                    $scope.tmp = $scope.date;
                }
            });
        }
    };
}]);

Prior to deployment, it's important to update the controller to utilize an array for its arguments as a safeguard against minification.

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

The development mode of NextJS is experiencing issues, however, the build and start commands are functioning normally

Just finished creating a brand new Next app (version: 12.0.7) using Typescript and Storybook. Everything seems to be working fine - I can successfully build and start the server. However, when I try to run dev mode and make a request, I encounter the follo ...

What is the most effective way to delete a single value from a key with multiple values stored in local storage?

This question has come up before, but the solutions provided didn't work for me, which is why I am asking it again. Currently, I am storing values in an array that is then stored in local storage. Here is the object: data.items - 0: {id: 190217270, ...

npm: Import a package from a GitHub repository that does not belong to me

I have encountered a package that I need for my project, but it is not available in npm. I am considering the option of uploading the package to npm myself. However, I am unsure if this is ethically or legally acceptable. What is your opinion on this mat ...

Is there a script available on this page that allows me to access the Google Chrome plug-in variable?

Could you kindly clarify if a script on the webpage is able to access variables from a Chrome extension? I have developed an extension for Google Chrome and am concerned about the possibility of the website owner where the extension is running being able ...

What methods can be used to avoid regular expressions when searching for documents in MongoDB?

I am using a simple regular expression-based search in MongoDB like this: router.get('/search', function (req, res, next) { var text = req.query.text; collection.find({text: new ReqExp(text, 'ig')}, function (err, result) { ...

Steps to implement a text border in Raphael.js

I have a website dedicated to creating customized football jersey designs. I'm utilizing Raphael.js for customization, and I am looking for a way to add an outline to text using Raphael. My research led me to the suggestion of using the stroke proper ...

How can we prevent components from rendering in React when their state or props have not changed?

I encountered a problem in my project where I have a main component that serves as the parent component of my project. Inside this main component, I have defined routes for other components and directly imported some components like a Side Navbar and Login ...

Ionic causing delay in updating ngModel value in Angular 2

My ion-searchbar is set up like this: <ion-searchbar [(ngModel)]="searchQuery" (keyup.enter)="search();"></ion-searchbar> In the typescript file, the searchQuery variable is defined as follows: export class SearchPage { searchQuery: string ...

Is it feasible to link an Angular property value to the value of an HTML data attribute?

Can an Angular property value be bound to a data attribute on a template element? <h1 data-name="{{name}}">Hello from {{ name }}!</h1> Example Link After running the code, it results in the following error: Error in src/main.ts (11: ...

Which JavaScript framework tackles the challenges of managing asynchronous flow, callbacks, and closures?

I have a strong aversion to JavaScript. I find it to be quite messy and disorganized as a language. However, I recognize that my lack of proficiency in coding with it may contribute to this perception. These past few days have been incredibly frustrating ...

Issue with thymeleaf causing malfunction in top-bar navigation on foundation framework

Looking for advice on creating a navigable menu using Foundation's "top-bar" component in an HTML template file with Spring MVC + thymeleaf. The menu bar appears but the sub-menus are not displaying when hovering over them. Sub-menus related to main ...

ReactJS incorporates multiple CSS files

I am currently working on developing a Single Page Application using ReactJS. However, I am facing an issue with styling. Currently, I have created 3 different pages (with the intention of adding more in the future), each having its own CSS file that is im ...

Issue with Ajax request not redirecting to correct URL

I have been successfully using ajax requests in my document without any issues. I am looking to retrieve the user's coordinates as they load the document and then pass this data on to other methods for distance calculations. On the loading of the ind ...

Can you explain what an express template engine is?

Having recently started working with express and angular development, I have a question about rendering views. Specifically: 1) What are the advantages of rendering a view via express using a template engine rather than solely relying on angular? 2) Is i ...

Merging two arrays together in JavaScript

Within my possession are two arrays: var g= [ { id: 36, name: 'AAA', goal: 'yes' }, { id: 40, name: 'BBB', goal: 'yes' }, { id: 39, name: 'JJJ', goal: 'yes' }, { ...

Exploring the TypeScript compiler API to read and make updates to objects is an interesting

I'm delving into the world of the typescript compiler API and it seems like there's something I am overlooking. I am trying to find a way to update a specific object in a .ts file using the compiler API. Current file - some-constant.ts export co ...

Using jQuery to make an Ajax post request that will load the current page with additional form data appended to the

Below is the HTML code for my registration form: <form id="registerForm"> <input type="text" pattern="[A-Za-z]{1,20}" placeholder="First Name" name="guestFName" title="Up to 20 alphabetical characters" required> <inp ...

Combining AngularJS with JWT and either WCF or WebAPI creates a powerful and

I am currently working on a small AngularJS application that utilizes AngularJS, TypeScript, and HTML5 for the user interface. I have successfully connected the UI to retrieve data from a Restful WCF service (written in C#). Everything is working well so f ...

Is there a way for me to retrieve the values of <td name="pname"> when the Edit button is

When the button is clicked, I use jQuery to add items in a td that I have created. $("#ddproduct").click(function () { $('#prodcuttable tr:last').after('<tr><td name="pname">' + prodName + '</td> <t ...

The script tag in NextJS is not properly loading the Amplitude library

I am facing an issue with loading events using Amplitude JS for tracking, despite having the correct code in place. Here is the code snippet that I used: import Document, { Html, Head, Main, NextScript } from 'next/document'; import Script from & ...