Last active
October 4, 2021 14:20
-
-
Save deepumi/5d9779c6ec3b91804df482fb7fb1b500 to your computer and use it in GitHub Desktop.
Validate Credit Card Expiry Month and Year.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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