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

Is there a way to retrieve the title, description, and image URL of a URL through Ajax, similar to how Facebook shares a link?

Currently, I am developing a project that involves allowing users to submit a URL. The system will then extract the title, images, and description from the provided URL and offer the option to toggle between different images. Upon submission, these extrac ...

Customized slider in jQuery UI allowing users to select height using a scaled ruler

Currently, I am tackling a challenging math problem related to adjusting the height selector input. Essentially, I have implemented a jQuery UI slider for choosing a height. It operates in inches and ranges from 0 to 120 (equivalent to 10 feet in height). ...

Tips for removing the "" character from a JSON string using JavaScript

At my node js server, I am receiving a json string that has the following format: {\"gID\":1,\"sID\":18,\"T\":\"Parking\"} I added the "\" in the string because it was created in C and the \ is used to es ...

Align boxes in the center within a DIV container

Here is the box design that I have created: The green color boxes are generated dynamically inside a "col-md-10" div. If there are less than 3 boxes in the second row, I would like to center align them. For example, in this case, I want the "Bi-monthly" b ...

Error: Attempting to access a property named '_updatedFibers' on an undefined object is not possible due to a TypeError

I encountered the following error: Uncaught TypeError: Cannot read properties of undefined (reading '_updatedFibers') at requestUpdateLane (react-dom.development.js:25411:23) at updateContainer (react-dom.development.js:28810:14) at ReactDOMHydra ...

Yearly Grouping with MongoDB's Aggregate Framework

I've been experimenting with the aggregate function to group date fields by year: db.identities.aggregate([ { $group : { _id : { year : {$year : "$birth_date"}}, total : {$sum : 1} } } ]) However, I encountered a c ...

Implementing a function to navigate to a different page using jQuery mobile

I'm attempting to pass a function when changing pages in jQuery Mobile, but I keep getting an error that points to `$.ajax` $( ":mobile-pagecontainer" ).pagecontainer( "change", "#schoolperformance", { reload : true, showLoadMsg : false, ...

What steps can be taken to enable CORS on an existing server that was created with createServer function?

The following code snippet is what I currently have: var gqlServer =require('./server.js') var server=gqlServer() var port = process.env.PORT||5000 server.listen({port:port}, ()=> console.log(` ...

Navigating to a different state key within a state object in React - a simple guide

Trying to dive into React, I encountered an issue. My goal is to create my own example from a tutorial. import React, { Component } from 'react'; class MyComponent extends Component { state = { persons: [], firstPersons: 5, variab ...

Keep track of the user's email address as they complete the form

I currently use a Google Form to gather information from employees who work in remote locations Emp No * Punch * Customer details / mode or travel All the data collected is stored in a Google spreadsheet structured as follows: Timestamp Emp No Punch ...

Add the JavaScript files to the components

I am working on integrating an admin template into my Angular2 project (version 2.1.0) which is already equipped with Bootstrap, jQuery, and jQuery plugins. Since there are numerous jQuery plugins and JS files involved, I am faced with the challenge of ho ...

Ways to refresh the count of newly added div elements

Currently, I am working on a socket chat program that requires a badge to display the number of users in the chat room every time a new user joins. The code snippet provided below shows a function that adds the name of the new user to the list. The added n ...

Retrieve the jQuery widget instance by selecting an element within the widget

I am currently developing a widget using the Jquery widget factory. The abbreviated version of the code looks something like this: _create: function(){ this.element.hide(); //hides original input element this.newInput=$("<input>"); //creates ...

Issue with AngularJS Directive - ng-click not activating within the specified directive

I've encountered an issue with my new directive. The variables are not being updated when using ng-click. I've searched and found some solutions here, but they all involve calling a method. I simply need to change the values of 2 variables when t ...

The generated hook in vuejs is throwing an error stating that window/localstorage is not defined

My goal is to save an authenticated user to local storage and then load them into Vuex on the next page load. created () { let user = window.localStorage.getItem('user') if(user) { this.setUser(JSON.parse(user)) } } I initia ...

Angular: the uncertain numeral formatter

Looking to customize the behavior of the Angular number filter? Want it to leave the input unchanged if it's not a number? <my-tag input-value="{{foo() | number: 2}}"></my-tag> If foo() outputs 1.2345, display 1.23, but if it's "abc ...

Tips for transferring data between iframes on separate pages

I am currently working on implementing a web calendar module within an iframe on page-b. This module consists of 1 page with two sections. Upon entering zipcodes and house numbers, the inputs are hidden and the calendar is displayed. The technology used he ...

obtaining the data stored in the backing bean and showcasing it upon submitting the form

I currently have an a4j:commandbutton implemented on my jsf page. Here is the code snippet- <a4j:commandButton id="submitBtn" value="#{msgsMass.MM_04_02_BTN_CONTINUE}" reRender="addNewCardForm,saveAddNewCardForm" immediate="true" action="#{bBea ...

My AngularJS module seems to be malfunctioning

After spending a significant amount of time on this, I am really hoping for some assistance. I am currently working on creating a module that will generate a directive and controller for the header section of my AngularJS site. Despite not encountering any ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...