Skip to content

Instantly share code, notes, and snippets.

@deepumi
Last active October 4, 2021 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save deepumi/5d9779c6ec3b91804df482fb7fb1b500 to your computer and use it in GitHub Desktop.
Save deepumi/5d9779c6ec3b91804df482fb7fb1b500 to your computer and use it in GitHub Desktop.
Validate Credit Card Expiry Month and Year.
using System;
public class Program
{
public static void Main()
{
var x = new CardExpiryValidator("10/2021");
Console.WriteLine(x.IsExpired);
}
}
public readonly struct CardExpiryValidator
{
private static readonly int _year = DateTime.Now.Year;
public readonly bool IsExpired;
public readonly int Month;
public readonly int Year;
public CardExpiryValidator(string cardExpiry)
{
ReadOnlySpan<char> chars = cardExpiry;
Month = default;
Year = default;
IsExpired = true;
int sliceIndex = 0;
if (chars.Length == 6 && chars.IndexOf('/') == 1) //9/2024
{
sliceIndex = 1;
}
if (chars.Length == 7 && chars.IndexOf('/') == 2) //09/2024
{
sliceIndex = 2;
}
Month = chars.Slice(0, sliceIndex).ToInt();
Year = chars.Slice(sliceIndex + 1).ToInt();
if (Month is < 1 or > 12 || Year < _year) return;
IsExpired = IsCardExpired();
}
private bool IsCardExpired()
{
var dateExpiry = DateTime.DaysInMonth(Year, Month);
var cardExpiry = new DateTime(Year, Month, dateExpiry, 23, 59, 59);
//Any future/current Month and Year is not expired.
//Expiry Date must be greater than Current Date.
var notExpired = cardExpiry > DateTime.Now;
return !notExpired;//Should return False if card is not expired.
}
}
internal static class IntegerExtensions
{
internal static int ToInt(this ReadOnlySpan<char> chars)
{
var val = 0;
for (var i = 0; i < chars.Length; i++)
{
if (!(chars[i] >= 48 && chars[i] <= 57)) return 0; //Skip if non integer character found.
val *= 10;
val += chars[i] - '0';
}
return val;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment