Validation for dates in Angular.Js input is important to ensure that only

Take a look at this form:

<form name="user_submission" novalidate="novalidate" method="post">
        <input type="date" name="date_of_birth" ng-focus="save_data()" ng-model-options="{timezone: 'UTC'}" ng-pattern="/^(19\d{2}|[2-9]\d{3})-(0?[1-9]|1[012])-(0?[1-9]|[12][0-9]|3[01])$/" ng-model="step_content.date_of_birth" required ng-maxlength="10" ng-minlength="10"  >
    <br>
                    <span class="error" ng-show="user_submission.date_of_birth.$error.pattern">Incorrect format!</span>
                    <span class="error" ng-show="user_submission.date_of_birth.$error.date">Incorrect Date!</span>
                    <span class="error" ng-show="user_submission.date_of_birth.$error.minlength">Incorrect Date!</span>
                    <span class="error" ng-show="user_submission.date_of_birth.$error.maxlength">Incorrect Date!</span>
</form>

This is the correct output from the form above:

https://i.stack.imgur.com/AUyB5.png

I want to limit the Year to 'yyyy' but I am still able to enter more than 4 digits.

https://i.stack.imgur.com/7RoHS.png

I attempted to use a directive for this purpose:

// Usage: <input limit-to="4" type="number" >

app.directive("limitTo", [function() {
    return {
        restrict: "A",
        link: function(scope, elem, attrs) {
            var limit = parseInt(attrs.limitTo);
            angular.element(elem).on("keydown", function() {
                if (this.value.length == limit) return false;
            });
        }
    }
}]);

However, when I apply the limitTo to the date field, I am unable to input a complete year. It seems like Angular is modifying the 'yyyy' by adding a number from the right and removing a 'y' from the left, making limitTo=10 ineffective.

I have run out of ideas.

Any assistance or guidance would be highly appreciated.

Thank you in advance.

Answer №1

I decided to create my own directive after giving up on finding a solution. I'll leave this question here in case it helps someone else facing the same issue.

Here is the directive I crafted, although a bit complex, it gets the job done across Chrome, Safari, and Firefox.

You can find the Plunker demo here: https://plnkr.co/edit/XwNR618DM8IULxu9KLMe

(Since I couldn't figure out how to link the Plunker address directly into the template, I embedded it within Plunker. Due to this embedding, the focus directive in the template doesn't work properly. However, implementing the code below will make sure your cursor moves from one textfield to another upon completion.)


app.directive('multiSelectDate', function () {
    // Directive logic here
});
...

To use this directive in your application, include the following HTML:

<multi-select-date datasource="date_of_birth" start-year="1945" ></multi-select-date>

To see the result, you can output the selected date like this:

{{date_of_birth}}

If you need to set an initial date in your controller, you can do so like this:

$scope.date_of_birth = '11/01/1950';

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

Enhancing user engagement with PDF files using AngularJS to create an interactive and captivating page-turn

Anyone familiar with how to achieve a page turner effect for PDF files using Angular? I'm open to jQuery solutions as well. I've come across turn.js, which uses HTML, but I'm specifically looking for a way to implement this effect with PDF f ...

Creating a series of neighboring rectangles with D3 that unintentionally produce a distracting shimmering effect

I've created a musical waveform using D3 by positioning rectangles next to each other. Check out the code here: http://jsfiddle.net/s4dML/ var data = [ 0.0534973, /* ...lots and lots of data... */ 0.290771]; data = data.filter(function(datum, index){ ...

Mobile devices do not support internal link scrolling in Material UI

Currently, I'm utilizing internal links like /lessons/lesson-slug#heading-slug for smooth scrolling within a page. While everything functions perfectly on desktop, it ceases to work on mobile view due to an overlaid drawer nav component. Take a look a ...

AngularJS - Error encountered while configuring $httpProvider with an unknown provider

In this code snippet: myApp.config(['$httpProvider', function($httpProvider, $cookieStore) { $httpProvider.defaults.withCredentials = true; $httpProvider.defaults.headers.get['Authorization'] = 'Basic '+ $cookieStor ...

javascript extract data from JSON

How can I extract values from the [object Object] in javascript? I have a JSON response from PHP that I am passing into JavaScript. I want to retrieve the GPSPoint_lat and GPSPoint_lon values. var jArray = ; var obj = JSON.parse(jArray); I am gett ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...

Updating token using an Ajax request in a PHP webpage

Currently, I am encountering an issue with my token system for requesting PHP pages via Ajax. The problem arises when attempting to make multiple Ajax requests from the same page as I am unable to refresh the token on the initial page. To elaborate furthe ...

I am having trouble displaying images with Material UI CardMedia

I'm currently using CardMedia to display images on my webpage, but unfortunately, the image is not appearing as expected. After researching a similar issue on Stack Overflow, I discovered that the suggested solution involved importing the image and t ...

The building of the module was unsuccessful due to a failure in the babel-loader located in the webpack module of Nuxt

While working on my Nuxt.js project, I encountered a warning error that I couldn't resolve even after searching for a solution. If anyone can assist me with this issue, it would be greatly appreciated. The error message is as follows: ERROR in ./.nu ...

Tips for integrating JavaScript libraries with TypeScript

I'm looking to add the 'react-keydown' module to my project, but I'm having trouble finding typings for it. Can someone guide me on how to integrate this module into my TypeScript project? ...

Unable to modify the state with a computed setter in VueJS

In my Vue.js project, I am trying to work with a form where the end_saving value needs to be computed based on the values of start_saving and duration. To achieve this, I want to utilize the saving.end_saving property in the v-model for submission via a PO ...

Tips for managing variables to display or hide in various components using Angular

In this example, there are 3 main components: The first component is A.component.ts: This is the parent component where an HTTP call is made to retrieve a response. const res = this.http.post("https://api.com/abcde", { test: true, }); res.subscribe((r ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

Uploading files into an array using Angular 2

Struggling to incorporate an uploader within an array: I've got an array of users displayed in a table using "ng-repeat". I want to add a column with a button to upload an image for each user. Currently, I'm utilizing ng2-file-upload, but open t ...

Improved Node.js algorithm designed to identify anagrams of a specific string in an array. The approach must not rely on generating all possible subsets to find the anagram of the string

I am looking to create a collection of anagram pairs within an array. The input will consist of the initial array of strings. For example: let inputArray = ["abcd", "dbac", "adfs", "adsf", "bDca"]; This program should consider the case of the letters, m ...

The Datepicker and Tablesorter dilemma

Having a Datepicker and Tablesorter on the same View Page presents an issue for me. When I remove the tablesorter, the datepicker functions properly. However, when I reintroduce the tablesorter, the datepicker stops working entirely. Below is the code sni ...

Leveraging dependency injection in Angular 2+ with pre-loaded models

I desire the ability to create an instance of a model using a constructor while also providing injected services to that model. To clarify, I envision something like this: var book = new Book({ id: 5 }); // creates instance, sets id = 5 book.makeHttpCa ...

Experience the quick sort programming algorithm in action using Vue.js without the hassle of dealing with Promises

I am currently experimenting with the quicksort algorithm visualization using Vue.js for self-educational purposes. However, I am facing some difficulties with async/await implementation. Although array filling and shuffling seem to work fine (although I a ...

Repairing the Performance of the 'Save' Feature

Can the 'Save' button in my code save team assignments for players selected using drag and drop? I'm considering using localStorage, but unsure about implementation. Note: To run the code properly, copy it as an HTML file on your computer. ...

Use Google Maps to plan your route and find out the distance in kilometers as well as the

Feeling a bit overwhelmed with the project I'm working on, but hoping for some guidance. We're aiming to create a form where users input a starting point and an ending point, similar to the examples on Google Maps (http://code.google.com/apis/ma ...