Validating date inputs with ng-change in AngularJS

I am currently utilizing AngularJS along with AngularJS bootstrap within my webpage. One of the components I have is a date picker directive that is structured like this:

    <div class="form-group {{dateStatus.class}}">
        <p class="input-group">
            <input type="text" id="inpDate" class="form-control" 
                   datepicker-popup="dd-MMMM-yyyy" ng-model="task.date" 
                   is-open="datePickerStatus.isOpen" min-date="minDate" 
                   datepicker-options="dateOptions" ng-required="true" 
                   close-text="Close" placeholder="Due date" 
                   ng-change="checkDateValidity()"
            />
            <span class="input-group-btn">
                <button type="button" class="btn btn-default" 
                        ng-click="openDatePicker($event)"
                >
                    <i class="glyphicon glyphicon-calendar"></i>
                </button>
            </span>
        </p>
    </div>

In order to validate the date input, I have implemented the following function in my controller:

        $scope.checkDateValidity = function(){
        var date,
            isValid,
            taskDate;
        taskDate = $scope.task.date;
        date = new Date(taskDate);
        isValid = !isNaN(date);
        if(isValid) {
            $scope.addButtonState.isOk = true;
            $scope.dateStatus.class = '';
        }
        else{
            $scope.addButtonState.isOk = false;
            $scope.dateStatus.class = 'has-error';
        }
    }

Currently, everything is functioning correctly in validating the entered date, however, I encountered an issue where when the date input is left empty (or changed from valid to blank), I want it to be considered acceptable as well. Due to both empty and invalid dates resulting in undefined, I am unsure how to differentiate between them.

I also contemplated directly reading the input text using this approach:

document.getElementById('inpDate').value

However, the ng-change event is triggered only when the value is altered, leaving me with the previous value which is now irrelevant...

Thank you for your time and any assistance provided.

Answer №1

One effective method for validation involves implementing a directive to include a Validation Rule.

.directive("validateDate", function() {
     return {
         require: 'ngModel',
         link: function(scope, elm, attrs, ctrl) {
             ctrl.$validators.validateDate = function(modelValue, viewValue) {
                 if(!isNaN(modelValue) || ctrl.$isEmpty(modelValue)){
                     return true;
                 }
                 return false;
             };
         }
     };
 })

Simply include validate-date in the input tag and the validation will indicate that the input is valid if it is not a number or empty.

Answer №2

To ensure the validation of the value in #inpDate, you can bind a validator callback to both the change and keyup events. When the callback is triggered, you can then verify the validity of the input.

$timeout(function(){        
    angular
        .element(document.getElementById('inpDate'))
        .bind('keyup change', function(){
            var inputValue,
                customDate,
                isValid;

            inputValue = this.value;
            if(inputValue != ''){
                customDate = new Date(inputValue);
                isValid = !isNaN(customDate);

                if(isValid){
                    console.log('Valid');
                    // do something
                }
                else{
                    console.log('Invalid');
                    // do something else
                }
            }
            else{
                console.log('Empty');
                // do something else
            }
        });
}, 400);

Ensure that you have injected $timeout in your controller.

Answer №3

To perform validation in this manner, you may utilize the following code snippet:

if(document.getElementById('inpDate').value === "" ){
            $scope.addButtonState.isOk = true;
            $scope.dateStatus.class = '';
}

Insert this block of code at the start of the $scope.checkDateValidity function.

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

Utilizing UI Bootstrap Pagination with ng-repeat to enhance the user experience of navigating through a dynamically generated table

Struggling with incorporating pagination into my Angular app using uib-pagination. I can't seem to figure out the correct approach. HTML <table id="mytable" class="table table-striped"> <thead> <tr class="table-head"> & ...

Angular's ui.bootstrap popover does not function as expected

Currently, my setup includes Angular 1.5.0-beta2, Bootstrap 3.3.5, and ui.bootstrap 0.14.3. The objective is to implement a popover on an li element. In the code snippet below, ng-repeat is employed on an array with the directive popover-template indicat ...

"Encountering a mysterious internal server error 500 in Express JS without any apparent issues in

My express.js routes keep giving me an internal server error 500, and I have tried to console log the variables but nothing is showing up. Here are the express routes: submitStar() { this.app.post("/submitstar", async (req, res) => { ...

Is there a way to validate form input before inserting it into a database using the onsubmit event?

Looking for a way to enhance the verification process of my signup form, I aim to ensure that all data entered is validated before being saved in the database. The validation process involves checking if the phone number consists only of numerical values a ...

Attempt to generate a function in JavaScript that mirrors an existing one

How can I create a javascript function similar to loadAllOriginal, but with the value of the variable allEmployees being a list of employee objects (ID, FirstName, LastName)? I am attempting to implement this method in combination with autocomplete from ...

Utilizing Jquery to pass two classes along

I am looking for assistance on how to pass multiple classes within if-else statements and jQuery. My goal is to have both divs and divs2 change when the next button is clicked. Can someone please provide guidance on achieving this? --code not mine-- ...

Using jQuery's each method to implement dynamic fallback with JSON data

Is it possible to set a fallback function dynamically from an AJAX JSONP call? I've been trying, but it doesn't seem to work. I'm not sure if I'm doing it right. Here's what I have: var GetFacebookData = function (data) { ...

Employing a function to concatenate promises

In my coding process, I have come across a situation where I need to fetch content and then save it using two separate functions. Each function performs a different task based on the type of content provided. These functions act as helper functions in my o ...

Combining element.scrollIntoView and scroll listener for smooth scrolling by using JavaScript

Can element.scrollIntoView and a "scroll" event listener be used simultaneously? I'm trying to create code that checks if the user has scrolled past a certain element, and if so, automatically scrolls smoothly to the next section. I attempted to achi ...

Sharing the outcome of a $.get request with another function for optimal results

I am facing an issue with the callback function of the jquery $.get() ajax function. Currently, I am working with the DataTables plugin and attempting to implement the "expanding row to see children details" example from (https://www.datatables.net/exam ...

Ways to attach the close event to the jquery script

Hello, I'm having trouble reloading the parent page when the close button is clicked on a modal dialog. Here's my code snippet: //customer edit start $( ".modal-customeredit" ).click(function() { var myGroupId = $(this).attr('data- ...

Requesting Axios.get for the value of years on end

I'm grappling with obtaining a JSON file from the server. The endpoint requires a year parameter, which needs to be set as the current year number as its value (e.g., ?year=2019). Furthermore, I need to fetch data for the previous and upcoming years a ...

How to access and retrieve data from a USB flash drive using Javascript

I am looking to print PDF files from a USB flash drive. I have decided to use Mozilla Firefox and the R-kiosk plugin along with the open library PDF.js, but I am facing an issue. How can I read folders and files to create a tree structure without using ...

Move files into the designated folder and bundle them together before publishing

Is there a way to transfer the files listed in package.json (under the File field) to a specific folder in order to bundle them together with npm publish? Here is the structure of my repository: . ├── package.json └── folder0 ├── fil ...

Extract the text content from an HTML file while ignoring the tags to get the substring

Hello, I am a newcomer to the world of Web Development. I have an HTML document that serves as my resume, formatted in HTML. For example: html <p>Mobile: 12345678891 E-mail: <a href="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Deactivate the form outside of normal business hours

I need to create a form for a delivery service that only operates from 9am to 9pm. If a user submits the form outside of these hours, I want to redirect them to a page displaying the company's operating hours instead of a thank you page. For instance ...

The not:first-child selector targets all elements except for the first one in the sequence

This is a simple js gallery. I am using not:first-child to display only one photo when the page is loaded. However, it does not hide the other photos. You can view the gallery at this link: (please note that some photos are +18). My objective is to hide ...

Navigating through each element of an array individually by using the onClick function in React

I'm currently working on a project that involves creating a button to cycle through different themes when pressed. The goal is for the button to display each theme in sequence and loop back to the beginning after reaching the last one. I've imple ...

Having difficulty retrieving a dropdown value with reactjs

Seeking assistance with retrieving dropdown values in ReactJS. Despite attempting multiple methods, I have been unsuccessful in obtaining the values. Can someone provide guidance on extracting these values? Below is a snippet of my code: <Grid container ...

Finding the difference or sum within an array to identify the two numbers that produce a new array

In order to clarify, I am looking for a method to identify the two smallest numbers in a sorted array that will result in a specific number when subtracted. The process can be broken down into the following steps: Iterate through the array and designate ...