Custom AngularJS directive for validating date input forms

My current project involves an Angular 1.5.3 app.

This is the task at hand:

I have a user form with two date input fields. I need to implement custom validation on the form so that if the "expiry date" is greater than the "effective date", an error message is displayed to the user.

I believe I can achieve this by creating a custom directive and utilizing ng-messages.

Below is a snippet of my code:

 <form name="form.mainForm">

      <div>
        <span>Effective Date: </span>
        <input required type="date" name="effectiveDate" ng-model="effectiveDate" />

        <div>
          <span>Expiry Date: </span>
          <input 
            type="date" 
            name="expiryDate" 
            ng-model="expiryDate" 
            date-greater-than="{{ effectiveDate }}" />
        </div>
      </div>
  </form>


app.directive('dateGreaterThan', function () {
      return {
                restrict: 'A',
        require: 'ngModel',
        scope: false,
        link: function (scope, elm, attrs, ctrl) {
            console.log(' here we are ');

            function isValidDateRange(expiryDate, effectiveDate) {

                console.log(expiryDate, effectiveDate);

                if (effectiveDate == null || expiryDate == null ) {
                    return true;
                }

                return effectiveDate > expiryDate;
            }

            function validateDateRange(inputValue) {
                var expiryDate = inputValue;
                var effectiveDate = scope.effectiveDate;
                var isValid = isValidDateRange(expiryDate, effectiveDate);
                console.log("isValid: ", isValid);
                ctrl.$setValidity('dateGreaterThan', isValid);
                return inputValue;
            }

            ctrl.$parsers.unshift(validateDateRange);
            ctrl.$formatters.push(validateDateRange);
            attrs.$observe('dateGreaterThan', function () {
                validateDateRange(ctrl.$viewValue);
            });
      }
      };

I've made an attempt to address this issue, but unfortunately, my directive is not functioning as expected. It does not update when the dates change and it does not integrate well with ng-messages.

Here is my attempt: http://jsfiddle.net/aubz88/q7n3abre/

Answer №1

To utilize the ngMessages module, it is recommended to either load it from a content delivery network (cdn) or install it using a package manager. Please note that the ngMessages module does not come pre-installed with AngularJS. You can find more information about it here: https://code.angularjs.org/1.4.14/docs/api/ngMessages

var app = angular.module("hello", ['ngMessages']);

Here are some additional pointers. Make use of the $validators feature provided by ngModel.

ctrl.$validators.dateGreaterThan = validateDateRange;

Ensure to pass the other date using a scope property

 scope: {dateGreaterThan: '='},

There are still areas for improvement and enhancements in this setup. It's also worth mentioning to consider triggering the validation again when the first date changes. You can refer to the $validate function of https://code.angularjs.org/1.4.14/docs/api/ng/type/ngModel.NgModelController.

You can view a basic implementation example in this fiddle: http://jsfiddle.net/hcjLkuzt/

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

Angular: The function t(...) does not support success - TypeError

My code is generating the error TypeError: t(...).success is not a function. I have tried searching for a solution but haven't been able to figure out why this error is happening in my specific case. Here is a snippet of my JS code. Can anyone point ...

Put a pause on running a JavaScript function until the one preceding it has completed

After successfully creating a product using a modal box form on my page, the modal disappears with an effect and the list of products on the page should be updated with the newly added item. However, the animation of the modal disappearing disrupts the fl ...

Enhance your bookmarking experience with Vue mixins that allow you to easily customize the color

Looking for a way to efficiently bookmark pages in my application, I have successfully implemented a feature where I can add pages by their name and URL into bookmarks. Upon clicking the bookmark button, it changes color to indicate that the page has been ...

Utilizing VueJS to Establish a Binding Relationship with Props

One of my Vue components is named Avatar.vue, and it is used to create an avatar image based on user-defined props. The parameter imgType determines whether the image should have rounded corners or not. Here is the code: <template> <div> & ...

Can you explain the meaning behind the exclamation mark in Angular syntax?

I've noticed this popping up in a few spots lately, but I haven't been able to find any information about it. I'm intrigued by the use of the '!' symbol in Angular syntax. Can anyone explain what it does? https://i.sstatic.net/sj ...

Can you explain the contrast between img.height and img.style.height?

I'm currently in the process of resizing a series of images by iterating through an array and adjusting their sizes. if(items[0].height > 700 || items[0].width > 700){ items[0].style.height = "700px"; items[0].style.width = "700px"; } As ...

Navigating Paths in Real-time with Javascript - Node.js

When working with PHP, dynamic routing can be achieved by defining classes and methods like: class Route { public function homePage () { echo 'You are on the home page' } public function otherPage () { echo 'You are on so ...

Production environment experiencing issues with Stripe functionality due to element remaining mounted

When making a payment in development mode, everything goes smoothly. However, when I switch to production, I encounter the following error message: v3:1 Uncaught (in promise) IntegrationError: We could not retrieve data from the specified Element. Please e ...

Detect a modification event on a field lacking an ID using jQuery

I'm currently facing some challenges with jQuery and I really need to overcome them in order to complete the code I'm working on. The issue is that I can control the img tag, but unfortunately, I am unable to assign an ID to the input tag as des ...

What is the best approach for scaling @material-ui Skeleton in a grid row with variable heights?

I am working on creating a grid of Avatar images with a transition state where I want to show a skeleton representation of the image. To achieve this, I am using @material-ui/lab/Skeleton. The issue I'm facing is that since my images are set to autos ...

Cannot work on repl.it; it seems to be incompatible with the freeCodeCamp - JavaScript Algorithms and Data Structures Projects: Roman Numeral Converter

Recently completed my Roman Numeral Converter and it functions correctly on repl.it. However, when testing it on freecodecamp, the output displayed: // running tests convertToRoman(2) should return "II". convertToRoman(3) should return "III". ... // tests ...

Tips for declaring a particular type during the process of destructuring in Typescript

I have my own custom types defined as shown below: export type Extensions = | '.gif' | '.png' | '.jpeg' | '.jpg' | '.svg' | '.txt' | '.jpg' | '.csv' | '. ...

Attaching an input text box to an Angular $scope is not possible

In my angular app, I have a piece of markup that showcases a table with saved queries. Each query has the option to add a title using an input field. When you click the edit icon, it should display the newly created title. <table class="table table-str ...

Creating text using the Bootstrap grid system

I am currently using Bootstrap and have set up a grid with a circle on the left side. I am now facing an issue where any text I try to add next to the circle overlaps with it. I need the text to not overlap with the circle and vice versa, while also being ...

How can a React app be developed offline?

I am currently working offline with no access to the internet. Node.js is already installed on my system, but I encountered an error when trying to run the command npm create-react-app. Is there a way for me to execute npm commands and set up a react app ...

Encountering an unexpected token in the JSON file at the very start is causing an

An unexpected error has occurred, showing the following message:- Uncaught SyntaxError: Unexpected token u in JSON at position 0 The code causing the error is as follows:- import { useEffect, useState } from "react"; import { useNavigate, usePar ...

Using Jquery to create an array containing all the items in the pager

192.168.1.1/home?page=1, 192.168.1.1/home?page=2, 192.168.1.1/home?page=3. Is there a way to create an array of only the new items on the pager? I am interested in storing only the elements with the class item-new into the array. To clarify further: I n ...

function not defined

(function($){ $.fn.slideshow = function(){ function init(obj){ setInterval("startShow()", 3000); } function startShow(){ alert('h'); } return this.ea ...

Streamlining all icons to a single downward rotation

I am currently managing a large table of "auditpoints", some of which are designated as "automated". When an auditpoint is automated, it is marked with a gear icon in the row. However, each row also receives two other icons: a pencil and a toggle button. W ...

Incorporate dynamic variables into your HTML code using jQuery or JavaScript

I'm struggling to generate HTML code from JavaScript/jQuery within an HTML template rendered in Django. I need to append HTML code and also insert some values in between. Currently, I am using a basic string append method like this: var features =[&ap ...