Converting milliseconds to a valid date object using Angular form validation

I am facing an issue with form validation and milliseconds in my Angular application. It seems that Angular does not consider time in milliseconds as a valid date format, causing the angular.isDate(1418645071000) function to return false.

How can I modify my code to ensure that form validation works properly? I have no restrictions with the server, so a date in the format "Sat Feb 03 2001 00:00:00 GMT+0100 (CET)" should also be acceptable.

Check out the code here: http://plnkr.co/edit/lZZh5VvCzH6yYh1t8xVM?p=preview

Answer №1

The solution I discovered was inspired by a discussion on stackoverflow found at this link

I have implemented a filter for the modelValue to achieve my desired custom date format, resulting in the viewValue being formatted as 'dd.MM.yy'.

ngModelCtrl.$formatters.push(function(modelValue) {
      if(modelValue) {
        var filtered = $filter('date')(modelValue, 'dd.MM.yy');
        return filtered;
      }
    });

In addition, I utilized the following code to promptly convert milliseconds to a valid date:

/*https://stackoverflow.com/questions/22639485/angularjs-how-to-change-the-value-of-ngmodel-in-custom-directive*/
    // $parse works out how to get the value.
    // This returns a function that returns the result of your ng-model expression.
    var modelGetter = $parse(attrs['ngModel']);
    console.log(modelGetter(scope));
    var timeInMilliseconds = modelGetter(scope);

    if(timeInMilliseconds != null) {
      // This returns a function that lets us set the value of the ng-model binding expression:
      var modelSetter = modelGetter.assign;

      // This is how you can use it to set the value 'bar' on the given scope.
      modelSetter(scope, new Date(timeInMilliseconds));
      console.log(modelGetter(scope));
    }

To reflect these changes, I have updated the relevant link: http://plnkr.co/edit/lZZh5VvCzH6yYh1t8xVM?p=preview. As a result, all validation errors have been resolved.

Answer №2

angular.isDate is a function that verifies if the input is a date object.

To convert milliseconds to a date, you can use the syntax new Date(milliseconds)

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

Does having an excessive amount of variable declarations result in a noticeable decline in performance?

One thing I notice for the sake of readability is that I tend to create new variables for data that I already have on hand. I'm curious, does this impact performance significantly? Here's an example of what I mean: const isAdult = this.data.per ...

What is the best way to extract a specific number from a table with Selenium, especially when the location remains consistent across all zip

Context: I am attempting to scrape data from a website with JavaScript using Selenium in Python. Goal: Extract a specific number from the table located at 159x26. I believed that this code would retrieve the number from row 159, column 26. Here is the c ...

JavaScript function overriding allows a subclass to provide a specific implementation of

I have a JavaScript file with two methods: var DBProcessing = function() { console.log("ok") ... } var DBProcessing = function(str) { console.log(str); ... } When calling DBProcessing(), I am only getting an output of undefined. Is there a way to expli ...

What is the best way to showcase distinct sections from several web pages on a single webpage?

I want to showcase multiple web pages on a single page using Iframes. What is the best way to achieve this and display them all together? ...

Guide on automatically attaching a file to an input file type field from a database

Currently, I am implementing a PHP file attachment feature to upload files. Upon successful upload, the system stores the filename with its respective extension in the database. The issue arises when trying to retrieve and display all entries from the ...

Issue encountered while utilizing combineReducers: "Error: The assetsReducer returned an undefined value during initialization."

Issue: The "assetsReducer" has returned an undefined value during initialization. When the state passed to the reducer is undefined, it must explicitly return the initial state, which cannot be undefined. If no value is set for this reducer, consider using ...

Toggle the sliding menu drawer option (upward/downward motion)

When it comes to my simple menu, I'm using jQuery to toggle the visibility of a few DIVs. The code is straightforward as shown below, and I could really use some assistance with adding extra functionalities. <div id="one" class="navLinks"> cont ...

Challenges with the Sumo Select Refresh Feature

I am having trouble with Sumo select not refreshing the data properly. The action method is returning the correct list, but it seems like the JQUERY multi-select rebuild() function is missing. Is there something I'm overlooking? $("#ddlCountry&q ...

The routing feature functions properly on localhost but encounters issues on the live server

There seems to be an issue with this code. While it works perfectly on localhost, it doesn't function as expected on a live Apache server. I have already specified the homepage in the package JSON file and included an htaccess file. However, when acce ...

How to display a page outside the router-outlet in angular 4

I'm currently developing an angular 4 application and I am trying to figure out how to load the login.page.ts outside of the router-outlet This is what my home.component.html file looks like: <div class="container"> <top-nav-bar></ ...

What is the technique for using JavaScript to implement styling on a <td> within an HTML table?

Can someone help me with applying JavaScript to an entire column in an HTML table? Here is the script I am currently using: I want to insert a line break after each comma in the Message column of the table. Can anyone point out what I'm doing wrong? ...

Using a React component to send data through a POST request to an API

When attempting to send a selected value from a Dropdown to an API using a POST request, I keep encountering a 405 (Method Not Allowed) error. Despite trying different ways to handle the onChange event, such as: onChange{(e) => this.onChangeHandler(e.t ...

Persist state in Vue by using the `vue-persistedstate` reducer

Currently, I am utilizing vue-persistedstate with specific modules that are set to be persisted using the path attribute. This setup is functioning smoothly. However, I encountered an issue when attempting to combine it with the reducer. In this scenario, ...

What is the proper way to invoke a variable-function in Node.js?

I have a function called `findPeopleByName` that queries the database for a specific username, but I'm not sure how to call it in my Node.js code. Here's what I have so far: // Retrieve user_name from POST request. app.post("/api/exercise/new-u ...

The selector often yields varying results when used in a traditional browser versus when it is utilized with Selenium

When using Firefox in the console, I can enter: $("a:contains('tekst')") and it will display: object { length: 1, ... } However, when attempting the same in firefox opened by behat with sellenium, I receive the error message: SyntaxError: An ...

Invalid function call detected, transitioning from Reactjs to Nextjs

After spending some time away from the ReactJS world, I decided to make a comeback and try my hand at NextJS. Unfortunately, I ran into an issue with an Invalid Hook Call. I'm in the process of transitioning my ReactJS project to NextJS. To illustrat ...

A guide on determining the return type of an overloaded function in TypeScript

Scenario Here is a ts file where I am attempting to include the type annotation GetTokenResponse to the function getToken. import { ConfigService } from '@nestjs/config'; import { google, GoogleApis } from 'googleapis'; import { AppCon ...

How do I navigate to the homepage in React?

I am facing an issue with my routes. When I try to access a specific URL like http://localhost:3000/examp1, I want to redirect back to the HomePage. However, whenever I type in something like http://localhost:3000/***, I reach the page but nothing is dis ...

Is there a way to create optional sections within a reusable component's template in a Vue 3 application?

Recently, I've been immersed in developing a Single Page Application (SPA) using the powerful combination of Vue 3, TypeScript, and integrating The Movie Database (TMDB) API. One interesting challenge I encountered was with my versatile movie card co ...

I am experiencing technical difficulties with my API resulting in a 500 Internal Server Error

My application involves managing products using CRUD operations. I am able to successfully make an HTTP request to the /api/deleteProduct route in order to delete a product based on its ID. However, the issue lies with creating a new product as the functi ...