What is wrong with my expiryDateFormatIsValid() and validateCardExpiryDate()?

  • Create a expiryDateFormatIsValid function which takes a field parameter representing the card’s expiry date field. It should return true if the field’s value complies with the MM/YY format, otherwise it should return false.

  • With the above utility functions out of the way, go back to the validateCardExpiryDate function. This function should return true if the value provided matches the MM/YY format (hint: delegate to expiryDateFormatIsValid ) AND if the date is in the future. In either case, it should use the flagIfInvalid function to mark the field as valid or not. It then has to return true or false depending on if the validation requirements are met or not.

// HTML code here!

<div data-cc-info>
		<input type="text" size="20" placeholder="Name Surname" />
		<input type="text" size="6" placeholder="MM/YY" />
</div>

My solution

/* flagIfInvalid()*/
	   const flagIfInvalid = (field, isValid) => {
		   field.classList.toggle('is-invalid', !isValid)
};

/* expiryDateFormatIsValid()
*/
	   const expiryDateFormatIsValid = (field) => {
		   const format = /^([1-9]|1[0-2])\/\d{2}$/.test(field);
}
/* validateCardExpiryDate() */
	   const validateCardExpiryDate = () => {
		   const field = document.querySelector('[data-cc-info] input:nth-child(2)');
		   let isValid = expiryDateFormatIsValid(field);

	if (isValid) {
		const [mm, yy] = field.value.split("/");
		const date = new Date();
		const tm = date.getMonth() + 1;
		const ty = date.getYear() - 100;
		if (+yy >= ty) {
			if (+yy === ty) {
				if (+mm < tm) isValid = false;
			}
		} else {
			isValid = false;
		}
	   }
	   flagIfInvalid(field, isValid);
	   return isValid;
}

Stranded with this error
image

Thanks !

Perhaps, i was able to pass the test with my improved solution here than i had before,

 /* expiryDateFormatIsValid()
	     return true if the field's value compiles with MM/YY format or otherwise*/
	   const expiryDateFormatIsValid = (field) => {
		   //const format = /^([1-9]|1[0-2])\/\d{2}$/.test(field);
		   return RegExp(/^(((0)[0-9]) |((1)[0-2]))(\/)\d{2}$/).test(field.value) || RegExp(/^\d\/\d{2}$/);
}

and

const validateCardExpiryDate = () => {
		   const target = document.querySelector('[data-cc-info] input:nth-child(2)');
		  const currentDate = new Date();
		  const ds = target.value.split('/');
		  const userDate = new Date(`20${Number(ds[1])}`, (Number(ds[0]-1) + 2));
		  const valid = (expiryDateFormatIsValid(target) && (userDate >= currentDate));
		  flagIfInvalid(target, valid);
		  return valid;
}

Now everything looks perfect. Thanks all

Hope this solution will help someone in the future when it’s need.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.