Checking dates in a JavaScript form

var myForm = document.getElementById("form");
document.bgColor="#FFFFCC";  //page styling
myForm.style.color="blue";
myForm.style.fontSize="20px";
myForm.style.fontWeight="400";
myForm.style.fontFamily="arial";

function validateForm() 
{
var firstname = document.getElementById("firstname"); 
var lastname = document.getElementById("lastname");
var postcode = document.getElementById("postcode");
var email = document.getElementById("email");
var cardtype = document.getElementById("cardtype");
var cardnumber = document.getElementById("cardnumber");
var ccv = document.getElementById("ccv");
var month = document.getElementById("month");
var year = document.getElementById("year");
  
if (firstname.value==""){
alert("Your first name can not be left blank");
firstname.focus();
return false;
}
if (lastname.value==""){
alert("Your last name can not be left blank");
lastname.focus();
return false;
}
if (postcode.value.length!=4){
alert("Your post code must be 4 numbers in length");
postcode.focus();
return false;
}
if (isNaN(document.getElementById("postcode").value)){
alert("Your postcode can not contain letters");
postcode.focus();
return false;
}
if (email.value.length<5 || email.value.indexOf("@")== -1){ 
alert("Your email must not be less than 5 characters in length, it must contain an @ and a .");
email.focus();
return false;
}
if (email.value.indexOf(".")== -1){ 
alert("Your email must not be less than 5 characters in length, it must contain an @ and a .");
email.focus();
return false;
}
if (cardtype.value == ""){
alert("Please enter your card type");
email.focus();
return false;
}
if (cardnumber.value.length!=16){
alert("Your card number must be 16 numbers in length");
cardnumber.focus();
return false;
}
if (isNaN(document.getElementById("cardnumber").value)){
alert("Your card number can not contain letters");
cardnumber.focus();
return false;
}
if (ccv.value.length!=3){
alert("Your ccv must be 3 numbers in length");
ccv.focus();
return false;
}
if (isNaN(document.getElementById("ccv").value)){
alert("Your ccv must be a number");
ccv.focus();
return false;
}
}

function checkDate(){ 
var date = new Date();
var month = date.getMonth()+1; 
var year = date.getYear()+1;
var expiryMonth = document.getElementById("month").value;
var expiryYear = document.getElementById("year").value;

if (month == expiryMonth)
{
alert("Your card has expired");
month.focus();
return false;
}
if (year == expiryYear) 
{
alert("Your card has expired");
year.focus();
return false;
}
return false;

}

function Popup(){
window.open( "file:///C:/Users/Andy2411/Desktop/4JSB/assignment/html/help.html", "myWindow", 
"status = 1, height = 500, width = 500, resizable = 0" );
return;
}
form{width:700px;margin:0 auto;}
#Div1{float:;width:300;height:300;border:2px solid;border-radius:10px;padding:10px;padding-bottom:20px;background-color:;box-shadow:0 0 10px #2DADAC;position: relative;  top: -5%;   transform: translateY(5%);}

#Div2{float:;width...
<!DOCTYPE html>
<html>
<head>
<title>Assignment4JSB</title>
<link rel="stylesheet" type="text/css" href="../css2/assignment.css" />
</head>
<body>
<form name=”userForm” autocomplete="on" id="form" onsubmit="return validateForm()">
<script src="../js2/assignment.js"></script>
<div id="Div1">
<h3>Order Form</h3>
<fieldset>
<legend>Enter your Details here</legend></br>
First name: <input type="text" id="firstname" size="30" />
<br /><br />
Last name: <input type="text" id="lastname" size="30" />
<br /><br />
Postcode: <input type="text" id="postcode" size="4" />
<br /><br />
Email: <input type="text" id="email" size="30" />
<br/><br/>
</fieldset>

<h3>Payment Details</h3>
<fieldset>
<legend>Please enter your payment details</legend><br/>
Credit Card  <select id="cardtype">
<option value=""></option>
<option value="Mastercard">Mastercard</option>
<option value="Visa">Visa</option>
<option value="AmericanExpress">American Express</option>
</select>
<br/><br/>
Card number  <input type="text" id="cardnumber" size="18"/>
<br/></br>
CCV  <input type="text" id="ccv" size="3"/>
<br/></br>
Expiry MM/YY  <select id="month" onsubmit="checkDate()">
<option value=""></option>
<option value="month">01</option>
<option value="month">02</option>
...    
<button type="submit" >Submit</button>
<button type="button" onClick="Popup()">Help</button><br/>
</div>
</form>
</body>
</html>

An assignment in JavaScript involves creating a basic form to validate user input. The code includes a function to check the expiry date of a credit card against the current date and providing users with a confirmation message upon successful submission. The task also requires increasing the size of the 'help' and 'submit' buttons and positioning them at the bottom of the form. However, there seems to be an issue with the date check functionality. Please find attached the progress made so far. Any assistance or suggestions would be greatly appreciated. Thank you.

Answer №1

Make sure to verify the year before checking the month.

if (year > expiryYear) //confirm that the current year is not expired
    {
        alert("Your card has expired");
        month.focus();
        return false;       
    }

if (year == expiryYear)
    {
        if(month >= expiryMonth) //ensure the current month is not expired
        {
          alert("Your card has expired");
          month.focus();
          return false;
        }       
    }

Alternatively, you can simplify it as

 if (year > expiryYear || ((year == expiryYear && month >= expiryMonth)) //check if the current  year has not expired
        {
            alert("Your card has expired");
            month.focus();
            return false;       
        }

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

Revise the text while keeping the column content unchanged

Is it possible to change the text in a column without affecting the image using Jquery? Can this be achieved solely with Jquery without any modifications to the HTML code? Check out the demo $(".jsNoWrap").text("Change text"); <script src="https://a ...

There was an error of TypeError that occurred due to the inability to access the property 'username' of an undefined

var express = require("express"); var app = express(); var morgan = require("morgan"); var mongoose = require("mongoose"); port = 8000; var User = require("./app/models/user"); mongoose.connect("mongodb://localhost:27017/tutorial", function (err) { i ...

Webpack has successfully built the production version of your ReactJS application. Upon review, it appears that a minified version of the development build of React is being used

Currently, I am implementing Reactjs in an application and the time has come to prepare it for production. In my package.json file, you can see that there is a "pack:prod" command which utilizes webpack along with a specific webpack.config.js file to build ...

Error: The value of 'id' cannot be assigned to an undefined property

Recently, I've been delving into learning JS Express and decided to create a basic solution to handle GET / DELETE / POST / PUT requests. Everything was running smoothly until I encountered an issue with the POST router. Below is the code snippet for ...

Combining two arrays with varying lengths based on their values

Seeking assistance with a programming task that is straightforward yet challenging for me. There are two arrays: one long and one short. var arrayShort = [ { id: 'A', name: 'first' },{ id: 'B', name: &ap ...

Is there a way in vee-validate to validate specific sections of a form?

I'm struggling with my English skills. When I utilize 'this.$validator.validate()', I am seeking a way to only validate specific inputs on the page. Is there a method to achieve this? ...

Deciphering JSON information extracted from a document

I am currently working on a Node JS project where I need to read a file containing an array of JSON objects and display it in a table. My goal is to parse the JSON data from the array. Below is a sample of the JSON data: [{"name":"Ken", "Age":"25"},{"name" ...

I need to update a JSON file on the server by adding a new object to the existing array using the fs.appendFile function

I have a JSON stored on the server like this: [{"a":1}, {"a":2}] and I'm wondering if there is a way to add an object at the end without having to rewrite the entire file on the server. As a workaround, I have been omitting the brackets and adding the ...

What is preventing me from being able to effectively transmit the array using the POST method in Express?

As a newcomer trying to learn Express, I believe I am on the right path, but I am currently facing some challenges with the POST method. The issue I'm encountering is as follows: Whenever I send a POST request to an HTTP file, I receive an empty ob ...

It seems that the JavaScript object is producing varied values in distinct locations despite no alterations made in between

I've encountered a puzzling issue where a variable is returning different values within a function, despite no modifications being made to it. This problem arises in a form component created using Vue.js (v2) that triggers a Vuex action. While I beli ...

Troubleshooting JQuery Variable Overwriting Problem

Here is the code snippet I am working with: <script> $(document).ready(function() { var settings_image ={ url:"<?php echo site_url('/cms/editor/upload/images');?>", method: "POST", fileName: "file", returnType: ...

Checking to see if all the users mentioned in the message have been assigned a role

Hello everyone, I'm new to asking questions here so please bear with me. I am trying to retrieve all the users mentioned in a message and check if any of them have a specific role, such as the staff role. Thank you for your help! Edit: Here is the ...

"Creating multiple circles on an HTML5 canvas using an iPad: A step-by-step guide

My current code is only drawing one circle at a time on an iPad view, but I want to be able to draw multiple circles simultaneously. How can I achieve this? // Setting up touch events for drawing circles var canvas = document.getElementById('pain ...

Return an array that has been filtered to exclude any elements that are also found in a separate array

I have an API that provides a list of cars. const getAsset = async () => dbApi('list_cars', ['', 100]) .then(result => result.map(e => e.symbol)); Here, the function getAsset returns the car list. 0: "BMW" 1: "HONDA" 2: " ...

Update the JSON data following deletion

I have received the following JSON data: "memberValidations": [ { "field": "PRIMARY_EMAIL", "errorCode": "com.endeavour.data.validation.PRIMARY_EMAIL", "createdDateTime": null }, ...

Adjusting image width using jQuery

I have been experimenting with creating a Webgl hover effect for an image. The effect works well, but now I am trying to specify a width for the image within jQuery. new hoverEffect({ parent: document.querySelector('.ticket'), intensity1: 0. ...

Creating a function to manipulate an element on a different webpage

Upon clicking a button on Page1, a function is triggered which then calls another function to generate HTML and append it to a div with the #lista id. The issue here is that #lista belongs to Page2, so I am unsure if there is a syntax similar to ajax where ...

The date entered in the input field should also appear in all other textboxes on the

I currently have 2 tables set up on my page. In the first table, there is a textbox (txt1) that includes a date picker. The second table contains 5 similar textboxes (txt2, txt3, txt4, txt5, txt6) also with date pickers. My requirement is as follows: Ini ...

Transform them into async/await in JavaScript

Exploring the promise-retry library, I discovered the following syntax: promiseRetry(function (retry, number) { return doSomething() .catch(retry); }) .then(function (value) { // .. }, function (err) { // .. }); Since I am utilizing a ...

Issue with Dynamic Image Path in Require Function: Unable to locate the relative module

I've been struggling with an error in VueJs require function for the past two days. I'm attempting to pass a prop to the Home component and then display the image. Home.vue <template> <BlogPost :post="welcomeScreen"/> <B ...