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

a stand-alone Node.js application connecting to a self-signed WebSocket (WSS) server

I am currently working with a node server (Meteor.js) that needs to communicate with another server using websockets. Since the communication is strictly between servers and does not involve direct users, I have decided to use a self-signed certificate. I ...

"Capturing the essence of your online presence: The

I recently completed a website for my Students Organization, which includes a special page dedicated to recognizing the individuals who helped organize our activities. Each member is represented with a photo on this page, sourced from their Facebook profil ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

What is the process for performing the "extract function" refactoring in JavaScript?

Are there any tools for extracting functions in JavaScript similar to the "extract function" refactoring feature available for Java and jQuery developers in Eclipse or Aptana? Or perhaps in another JavaScript/jQuery IDE? ...

What is the most effective way to verify email addresses within a pandas data frame?

I am dealing with a dataframe (df) that includes emails and corresponding euro amounts: email euro 0 <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d4dbc0c1c6dcd3dfd7f2d4dbc0c1c6d6dddfd3dbdc9cd ...

Encountering a User Agent error while trying to update Vue to the latest version using N

I was interested in experimenting with staging.vuejs. When I tried to install it using the command npm init vue@latest, I encountered an error. Here is the link for reference: https://i.stack.imgur.com/rCipP.png SPEC Node : v12.13.0 @vue/cli : v4.5.15 ...

Adding a third-party script after closing the body tag on specific pages in NextJS can be achieved by using dynamic imports and

In my NextJS application, a third-party script is currently being loaded on all pages when it's only needed on specific pages. This has led to some issues that need to be addressed. The script is added after the closing body tag using a custom _docum ...

Filtering out Objection/Knex query results based on withGraphFetched results

I am working with two models in Objection - "brands" and "offers". Brand: const { Model } = require('objection') class Brand extends Model { static get tableName() { return 'brands' } ...

javascript string assignment

Is it possible to conditionally assign a string based on the result of a certain condition, but for some reason, it's not working? var message = ""; if (true) { message += "true"; } else { message += "false" } console.log(message); ...

Attempting to generate a cost estimator, however, no results are showing up upon clicking the calculate button

Having based my code on a template and being fairly new to Javascript, I expected everything to work smoothly. However, upon testing it, I encountered an issue where nothing was displayed in the results boxes. My goal is to develop a pricing calculator th ...

Generate random images and text using a script that pulls content from an array

My goal is to have my website refresh with a random piece of text and image from an array when a button is clicked. I have successfully implemented the text generation part, but I am unsure how to incorporate images. Here is the current script for the text ...

Tips for streamlining the array filtering process

Is there a way to simplify the code to avoid repetitive use of lowercase and includes condition for each property? items() { return this.table.filter.keyword ? this.dataArray.filter( item => item.nombre.toLowerCase().includes(t ...

"Error message 'querySelector' property or method is not supported on this object" is displayed when trying to access the website using the machine name in Internet Explorer 11

I am facing an issue with my AngularJS site deployed on IIS in a Windows Server 2012 R2 environment behind the firewall. When accessing the site through RDP on the server and typing in http://localhost/Foo in Internet Explorer 11, everything works fine ...

Having difficulty in closing Sticky Notes with JavaScript

Sticky Notes My fiddle code showcases a functionality where clicking on a comment will make a sticky note appear. However, there seems to be an issue with the Close Button click event not being fired when clicked on the right-hand side of the note. I have ...

What is the best way to update configuration settings such as the host name when deploying with Gulp?

Currently developing a web application with AngularJS and utilizing Gulp for the build process. The app retrieves data from various APIs within AngularJS. However, a challenge arises during deployment as I need to use different host names depending on whet ...

Error: The program encountered a type error while trying to access the '0' property of an undefined or null reference

I am a beginner in the world of coding and I am currently working on creating an application that allows users to add items to their order. My goal is to have the quantity of an item increase when it is selected multiple times, rather than listing the same ...

After Effects Script: Apply various character styles from main text to subtext

I'm currently working on an After Effects script that can transfer the style and text of a text layer to another text layer in a different comp. The script works perfectly if the parent text layer only has one style, but I need it to handle a situatio ...

Transform js into a more dynamic format to avoid redundancy when displaying items upon click

I came across a simple lightbox code snippet, but it's based on IDs and I plan to use it for more than 20 items. I don't want to manually write out 20 JavaScript lines when there could be a more efficient way to handle it dynamically. My JS skill ...

Unusual occurrences within stacked MUI Popper components

Below is a sample Node component that uses a button element to anchor an MUI Popper: type Props = { children?: React.ReactNode; }; const Node = ({ children }: Props) => { const [anchor, setAnchor] = React.useState(null); return ( <div> ...

Identify the quantity of dynamically added <li> elements within the <ul> using jQuery

I'm facing an issue where I need to dynamically add a list of LI items to a UL using jQuery. However, when I try to alert the number of LI elements in this list, it only shows 0. I suspect that it's because the code is trying to count the origina ...