Tips for handling an incorrect date entry when a field loses focus in AngularJS

If I have an <input> field with the type='date' attribute in its untouched state, it displays mm/dd/yyyy as the date format. I am looking to see if there is a way to utilize AngularJS ng-blur directive to reset the field to this original format when a user enters data, for example 03/21/2016, deletes a character (e.g., 03/dd/2016), and then clicks outside of the field ('blurs').

Answer №1

Utilizing ng-blur

Insert this code in your HTML file:

<input type="date" ng-model="selectedDate" ng-blur="checkIfValid()" />

Add this function to your controller:

$scope.checkIfValid = function()
{
    // Validate the selected date
    // Reset to null if invalid
    $scope.selectedDate = null;
}

For more information, visit:

https://docs.angularjs.org/api/ng/directive/ngBlur

Answer №2

When coding your HTML

<input type="date" ng-model="date" ng-blur="checkDate(date,$event)" />

In your JavaScript

$scope.checkDate = function (inputDate, event) {
          if (!event.ctrlKey && !event.metaKey && (event.keyCode == 32 || event.keyCode > 46))
              formatInput(event.target);
          if (event.target.value.length == 10) {
              $scope.validateDate(1, event.target.value);
          }
      }

      //id is used for date control check
      //method validates entered date in MM/dd/yyyy format
      $scope.validateDate = function (id, dateValue) {
          var formats = ['MM/DD/YYYY']
          if (!moment(dateValue, formats).isValid()) {
              if (id == 1) {
                  $scope.date = null;
              }
          }
      }

I hope this solution works for you as well, it solved my issue.

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

Blocking negative values when a button is clicked in Vue.js using v-on:click

How can I prevent the counter from going below 0 when clicked in this Vue component? Do I need to create a separate method to block it? Thank you for your assistance. <button v-on:click="counter.document -= 1">-</button> <h3>{{coun ...

Make an ajax request to a method in YII framework

I need to send an AJAX call to a function within the directory structure outlined below: Yii::$app->request->absoluteUrl."protected/humhub/modules/post/controllers/PostController/UploadMusicFile"; Here is my view function: function uploadImage ...

How can I change the nested Material UI component style from its parent component?

I am currently incorporating a component from an external library into my project. However, I am facing limitations in customizing its style, especially when it comes to a button that is using material ui styles. Upon inspecting the element, I can see that ...

Policy regarding copyright content removal and protection of privacy

In the majority of musical websites I have come across, they often mention the following in their policies: At this particular website (www.Indiamp3.com), you will find links that redirect to audio files. These files are hosted elsewhere on the internet a ...

NG-model not visible to AngularJS Controller's filter

Finally, the code is working perfectly. It's a mystery to me. I created a custom filter to use with ng-repeat. The code is implemented within a Controller ... .controller('makeOrderController', function ($scope, $timeout, $ionicLoading) { ...

What is the best way to place a parent div above its child element?

I'm currently dealing with a container div styled with background-color: red;. This container has around 12 children, and the last child is set with background-color: blue;. My goal was to position the container on top of the child with the blue backg ...

Clicking two times changes the background

I am facing an issue with three boxes on my website. Each box is associated with a corresponding div. When I click on any box, the div displays and the background color turns red. However, when I click on the same box again, the div disappears but the back ...

"Pushing elements into an array does not function properly within a promise

I'm having trouble with my code - the push method isn't working and it's not returning anything. import {nearbyUsers, getLatitude, getLongitude} from './helper' const users = [] nearbyUsers(session, getLatitude(), getLongitude()).t ...

Having trouble with jQuery on my webpage

Looking for assistance with a technical issue I'm facing... I am currently working with AngularJS and have integrated jQuery into my project. However, I've encountered an issue where the jQuery code is not functioning as expected on the HTML pag ...

Switch between selecting every group of 3 items and every group of 4 items

Having an array with more than 14 items, I need to group them into 2 different groups in this specific way: The first 3 (#1,2,3) will be in array A, the next 4 (#4,5,6,7) will be in array B, the following 3 (#8,9,10) will be in array A, the subsequent 4 (# ...

What is the best way to create direct links to tabs using #anchors in JavaScript?

I am managing a website that includes info-tabs based on a template I found at this link. The tabs contain anchors like example.com/#convey, but unfortunately, direct links to specific tabs using #anchor do not work properly due to the tabs relying on Java ...

Verify the position of the scrollbar without triggering any reflow

Here is a function I have: is_bottom: function() { if (settings.scrollBottomOffset === -1) { return false; } else { var scroll_height, scroll_top, height; scroll_height = ...

Using JavaScript and node.js, make sure to wait for the response from socket.on before proceeding

My task involves retrieving information from the server on the client side. When a client first connects to the server, this is what happens: socket.on('adduser', function(username){ // miscellaneous code to set num_player and other variabl ...

Updating user data when logged in on multiple browsers can be tricky. Here's how to make sure that

I am currently using the express-session middleware to store user sessions in a Mongo collection. What is the most effective way to update all user sessions when changes are made from one session? For instance, if a user updates their email in session A, ...

CSS - Make the entire div clickable while leaving a specific area non-clickable

I have a block containing some information. Within this div is a hidden button labeled .remove. Clicking on the main block will take you to another page, while hovering over the div will reveal the button. However, clicking the button also navigates you aw ...

ng-model does not function properly with ng-repeat in a dropdown menu

I am trying to display images in an option list using ng-repeat because I couldn't achieve it with ng-options. However, I am facing an issue where I am unable to retrieve the selected value from ng-change. It seems like ng-model is not working as expe ...

The "div width 100%" property functions flawlessly when tested locally, yet fails to operate on the live server

Hello, I recently launched my new website at www.leafletsdistributors.com. However, I'm encountering an issue with the Get in touch section (the light grey colored area). Despite setting the width to 100%, it's not fully extending across the scre ...

Tips for obtaining accurate response from axios

When utilizing axios, I receive my query response in the format of response.data.response.object. Is there a way to access the answer directly without going through response.data first? ...

The angularjs datepicker functionality is functioning well, however there seems to be an issue with changing the year directly

Although the datepicker in my application is functioning correctly, I am facing an issue where I cannot change the year directly. Instead, I have to navigate month by month to switch years. This is the directive for the datepicker: app.directive('ad ...

Iterating through elements within a Div will retrieve the initial element exclusively

Is there a way to loop through all elements within the MainDiv Div in order to retrieve their values? Currently, I am only able to retrieve the value of the first element. <div id="MainDiv"> <input type="text" id="MyText"value="Text1" /> ...