Validating Credit Card Expiration Dates in AngularJS Form

I recently started learning AngularJS and decided to create a credit card validator. I successfully implemented the Luhn Algorithm in a custom filter, but now I'm facing issues with validating the expiration date as well. The conditions for a valid expiration date are as follows: - 08/16 - 02/2015 - 0518 - the date must not be expired.

Since I discovered that Angular already has a built-in date filter, I attempted to create one. However, my code doesn't seem to work as expected. Here's what I have:

/**
* validate-expiry-date Module
*
* Validates the date format and ensures it is not in the past
*/
angular.module('validate-expiry-date', []).filter('validDate', [function () {
  return function (date) {

    var currentDate = new Date();
    var month, year, day;

    if (/^\d{2}\/\d{2}$/.test(date)) {
        month = date.substring(0, 2);
        year = 20 + date.slice(-2);
        day = new Date(year, month);
        return(currentDate > day);
    }if (/^\d{2}\/\d{4}$/.test(date)) {
        month = date.substring(0, 2);
        year = date.slice(-4);
        day = new Date(year, month);
        return(currentDate > day);
    }else if (/^\d{4}$/.test(date)) {
        month = date.substring(0, 2);
        year = 20 + date.slice(-2);
        day = new Date(year, month);
        return(currentDate > day);
    };
  }
}])

Can anyone help me understand what might be wrong with my code? Thanks, B.

Answer №1

Your filter function is working conceptually, but there seems to be an issue with your interpretation of months (it's off by one). I recommend checking the documentation on the Date constructor for clarification.

The problem lies in fitting your function into Angular's expectations. Instead of receiving a single date string, you are actually handling the full array that needs filtering. Furthermore, instead of just returning true/false, you should modify and return the filtered array.

Fortunately, the function you created aligns perfectly with Array.prototype.filter, making it functional in this plunker I've corrected here.

Below are the relevant changes:

function filterSingleDate(date) {
    var actualDate = new Date();
    var m, y, d;

    if (/^\d{2}\/\d{2}$/.test(date)) {
        m = date.substring(0, 2) - 1;
        y = 20 + date.slice(-2);
        d = new Date(y, m);
    } else if (/^\d{2}\/\d{4}$/.test(date)) {
        m = date.substring(0, 2) - 1;
        y = date.slice(-4);
        d = new Date(y, m);
    } else if (/^\d{4}$/.test(date)) {
        m = date.substring(0, 2) - 1;
        y = 20 + date.slice(-2);
        d = new Date(y, m);
    }

    return actualDate > d;
}

var FilterModule = angular.module('FilterModule', []).filter('validDate', [function () {
  return function (dateList) {
    return dateList.filter(filterSingleDate);
  };
}]);

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

The method piSession.buildPageInteractionSession is not valid

Hey there! I am facing an issue with a simple AJAX call to a PHP file. The request should be sent to the server and return back in an HTML input field. Unfortunately, I have not been able to resolve this error so far. Below is the code snippet: HTML: ...

Tips on dividing and recycling mongodb connection in Node.js

I am currently troubleshooting the connection to MongoDB using Node.js. The code I have in a file named mongodb.js is as follows: const mongoClient = require('mongodb').MongoClient; const env = process.env.NODE_ENV || 'development'; co ...

The external Jquery file is being successfully loaded, however, the Jquery functions are failing to execute

I'm having an issue with my HTML partial, main index.html, and external JQuery file. Even though the file is being loaded successfully (verified through an alert function), the JQuery functions are not executing as expected. Upon checking the resourc ...

Angular 2: Applying class to td element when clicked

I am working with a table structured like this <table> <tbody> <tr *ngFor="let row of createRange(seats.theatreDimension.rowNum)"> <td [ngClass]="{'reserved': isReserved(row, seat)}" id={{row}}_{{sea ...

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...

Is the JavaScript Date object consistently displayed in the America/New_York timezone?

The server sends me a time-stamp in milliseconds (Unix time / time from Epoch) with the constant timezone "America/New_York". On my client side, I want to ensure that the time is displayed according to the America/New_York timezone. I have been using Joda- ...

How can you verify the presence of an object containing specific data within an array using JavaScript?

Currently, I am working with the Vue programming language and have some demo code to showcase: <template> <button @click="checkInList">Check</button> </template> <script> import { ref } from "@vue/reactivity& ...

Struggling to establish object notation through parent-child relationships in Angular 2

Hi there, I am new to Angular and JavaScript. Currently, I am working on achieving a specific goal with some data. data = ['middlename.firstname.lastname','firstname.lastname']; During the process, I am looping through the .html usin ...

Store a collection of objects in an array and assign it to a variable in JavaScript within a React application

Is there a way to loop through this Json data and extract the attribute values into an array for insertion into a constant variable in React? For example: { "data": [ { "id": "1", "type": "vid ...

Obtaining the distinct identifier of a MongoDB document during insertion

I am currently developing a NodeJS express application with MongoDB (using Mongojs) and I am facing some challenges in achieving a specific task. My issue is related to inserting an object into a collection and then obtaining the unique identifier of this ...

Encountering the error message "Error: Unable to process rejection (TypeError): that.setState function is not defined" while using ReactJS

I've been working on a dynamic chart that changes based on the Slider value. I did some research and everyone suggests that I need to bind it to resolve this error. However, no matter how many times I try to bind the function in different ways, I keep ...

Making AngularJS 'PUT' requests: The process of submitting only the data in a form

I am facing an issue while updating user data in Angular. When I send a 'PUT' request, the entire user $scope is being sent instead of only the fields visible on the form. To retrieve and update the data, I am using a Factory. Below is my edit f ...

Add a CSS class to the text that is selected within a Content Editable div

Hey there, I'm having an issue where the class is being applied to the button when pressed instead of the selected text. Here's my current code: The button needs to be a div, but it might be causing the problem. I just want the highlighted text ...

Running of code in <script> tag

At what point does the code inside script tags start executing? Does it happen in order? <html> <head> <title>Canvas tutorial</title> <script type="text/javascript"> function draw(){ var canvas = document.getElementById ...

What could be preventing this AJAX call from running correctly?

I am in the process of developing a website that provides users with a discount based on a promotional code they can input. It is important for me to verify the validity of the code in our database before allowing a new sign-up to proceed. Below is the AJA ...

Transferring information between a modal and a controller

Looking to make data accessible in a controller? I've put together a simplistic Plunk to demonstrate displaying data on the $scope within a modal. The goal is to be able to update the data, with changes reflected in the $scope only upon clicking "ok". ...

Tips for maximizing performance in ember-data through r.js

After making the switch to ember-data#canary, I encountered a problem with r.js failing. [Error: Error: ENOENT, no such file or directory '/scripts/lib/ember-data/ember-data/core.js' In module tree: app/main app/app embe ...

How should endpoint functions be correctly written for Mongoose in conjunction with Express?

While developing the backend API for my app, I have come across numerous examples of different approaches to handling errors in endpoint functions. The two options presented below illustrate this: Option 1: export const deleteProject = asyncHandler(async ...

Exploring the functionalities of JavaScript methods and nested components within Vue.js

Learning Vue.js has been an interesting experience for me. However, I am facing challenges with methods and child elements in the library. It seems like there is something simple that I am overlooking. In my current project, I have list items rendered on ...

Django Ajax filter displaying issue on HTML page

I'm uncertain about the correctness of my Ajax implementation. When using Django's built-in tags, the objects I pass through Ajax are not appearing on my template HTML page. view_results.html <div> <input id="search" name="search" t ...