Confirm that the time specified is in the future

My goal is to ensure that the time and date entered in my form are not in the past.

Currently, I have separate input boxes for the time and date, each validated using ng-pattern. How can I display an error (ng-invalid) when both input boxes combined result in a date from the past?

While I can perform the past vs. future calculation using moment.js, I am unsure how to handle the combination of these two input boxes. Can a directive only work on a single element, not two?

<input type="text" ng-model="startTime" ng-pattern="/^(?:\d|[01]\d|2[0-3]):[0-5]\d$/">
<input type="text" ng-model="startDate" ng-pattern="/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/">

Answer №1

To ensure both elements are validated simultaneously in your controller when any value changes, consider using the scope.$watch method.

Answer №2

Consider using a different input type like datetime to combine both the startTime and startDate into one startDateTime. By setting the max and min values, you can easily validate whether the input is in the past or future.

https://docs.angularjs.org/api/ng/input/input%5Bdatetime-local%5D

<input type="datetime-local" id="exampleInput" name="input" ng-model="startDateTime"
  placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />

Answer №3

After much deliberation, this is the solution I came up with. It relies heavily on the model, which may not be ideal, but it gets the job done.

m.directive("futureDate", function () {
    return {
        require: "ngModel",
        scope: false,
        link: function (scope, element, attrs, ngModel) {

            ngModel.$validators.futureDate = function (modelValue) {
                var time = attrs["futureDate"] == "time" ? modelValue : scope.startTime;
                var date = attrs["futureDate"] == "date" ? modelValue : scope.startDate;

                var datetime = moment(date + "T" + time);

                return datetime > moment();
            }
        }
    }
});

How to use:

<input type="text" ng-model="startTime" data-em-future-date="time">
<input type="text" ng-model="startDate" data-em-future-date="date">

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

What could be causing the .hover function to malfunction and how can I make it so that the .hover function only applies within the corner radius area?

I am attempting to make circles react to my jquery .hover function. Below is the JavaScript code I am using: jQuery.fn.center = function () { this.css("position","absolute"); this.css("top", Math.max(0, (($(window).height() - this.outerHeight()) / 2) + ...

Learn the process of assigning a value to a dynamically created textbox using JavaScript in code behind

To create a textbox in the code behind, I use the following method: TextBox txt = new TextBox(); txt.ID = "txtRef" + count + dr["DataField"].ToString(); div.Controls.Add(txt); I have been attempting to set the value for this textbox within a jQuery funct ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

Using AngularJS to auto-fill input and textarea fields

In order to test local storage, I created a ToDo list using angularJS. Within my mainController, the following code snippet is present: $scope.saved = localStorage.getItem('todos'); $scope.todos = (localStorage.getItem('todos') !== n ...

AngularJS - Creating a dynamic wizard experience using UI-Router

I have set up my routes using ui-router in the following way: $stateProvider .state('root', { url: "", templateUrl: 'path/login.html', controller: 'LoginController' }) .state('basket&a ...

How to extract a variable from a mongoose find method in a Node.js application

Within my Node.js program, I utilize my Mongoose database to query for a specific value in a collection, of which there is only one value present. var myValueX; myCollection.find(function(err, post) { if (err) { console.log('Error ...

Guide on how to use JavaScript to make an HTML5 input field mandatory

I am facing an issue with setting input fields as required based on radio button selection in a form. Initially, all fields should have required=false, but I'm unable to achieve this. No matter what value I assign to the required attribute, it always ...

Access Flask variable in JavaScript code

Currently working on a CTF challenge, my query is not seeking assistance in solving it, but rather pertains to syntax. The task involves retrieving the secret key from Flask server's configuration. This key is stored within the app.secret_key variable ...

Acquiring XML data directly in jQuery without any preprocessing

Hey there, I'm dealing with an unusual situation. I need to extract data from an API that returns malformed XML. Each <episode> in the response has its own <title> tag. However, when using $.get or $.ajax, all these titles end up in the &l ...

Is it possible to simultaneously play several one-shot sound effects on mobile web browsers?

I'm attempting to trigger a sound effect when the user clicks a button on my web application. Initially, I experimented with this approach: var sound = new Audio("soundeffect.ogg"); function clickHandler(){ sound.play(); } Unfortunately, if the ...

Render multiple checkboxes with values from an array of objects passed as a prop to a child component using a v

I am facing an issue with my Vue components 'Parent' and 'Child'. Each child component has a checkbox with a :checked prop. In the Parent component, I iterate through an array of objects and pass props to the child. Although I can emit ...

Invoke the parent's function within the Local-Registration component of VueJs

I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...

Enhance Your Website with Dynamic Autocomplete Feature Using jQuery and Multiple Input Search Functionality

I am working on a form with three input fields. Here is the HTML structure: Name<input type="text" class="customer_name" name="order[contact][first_name]"/><br/> Email<input type="text" class="customer_email" name="order[contact][email]"/& ...

Filtering content with a sliding effect using CSS and JavaScript

I'm currently developing a jQuery mobile app that requires filtering posts on a specific page. I have already added the posts and designed the filter. Take a look at how it appears below: https://i.sstatic.net/mVh9X.png I am working on animating th ...

Installation of Angular-cli was unsuccessful

Can you assist me with a query? I attempted to install the angular-cli using the npm command npm install -g angular-cli, but I encountered numerous error messages and the 'ng' command isn't working. Some of the errors I received include: ...

Tips for managing the number of items returned in a dataProvider using AS3

*Hey there! I'm looking to only display 100 items in a list component from a dataProvider, even if it contains more than 500 or even 1000 items. Specifically, I want the first 100 items with cameras on to be included, and then fill the rest to reach a ...

Issue with React nodemailer: net.isIP() is not a valid function

I'm currently working on a contact page in React and facing difficulties with the email functionality. My attempt involves using nodemailer and here is the snippet of my code: var nodemailer = require('nodemailer'); var xoauth2=require(&ap ...

After minimizing the window, the jQuery slider animation sped up significantly

I am currently using a coda slider on my website, but I have encountered an issue where the content slider plays too fast after the window is minimized. I believe this may be related to the use of SetTimeout, but I have not been able to find a perfect so ...

My Node.js script seems to be experiencing some issues

Could you provide me with a helpful tip? Here is the code I am working on: const request = require('request'); const cheerio = require('cheerio'); function getUrls(url) { const baseUrl = 'https://unsplash.com'; let u ...

Adjust the variable value if the "for" loop encounters an error

In my situation, I have a spreadsheet that contains a script responsible for checking another linked spreadsheet for a customer's name and then returning the associated code. Everything works smoothly when the customer name is found in the "CustomerCo ...