Validating Manual Credit Card Expiry - Solution

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.
9 years ago
Thought this might help someone else as there are no other post in the forum I could find that addressed this problem.

After collecting manual credit card numbers on my website for many years, people often forget to change the default expiry date. I am currently upgrading to nopCommerce , and the Manual Payments Plugin currently doesn't validate the expiry to make sure it is not in the past (e.g. as of today it defaults to 01 / 2014) Only took me about 5 hours to get the Rules correct as I've never used FluentValidation before!

So here are the rules I've added to ensure the expiry date is current.

Add to Nop.Plugin.Payments.Manual.Validators.PaymentInfoValidator

RuleFor(x => x.ExpireYear).Must(x => Convert.ToInt32(x) >= DateTime.Now.Year).When(f => !String.IsNullOrEmpty(f.ExpireYear)).WithMessage("The credit card expiry date is invalid.");

RuleFor(x => x.ExpireMonth).Must(x => Convert.ToInt32(x) >= DateTime.Now.Month).When(f => !String.IsNullOrEmpty(f.ExpireMonth) && !String.IsNullOrEmpty(f.ExpireYear) && Convert.ToInt32(f.ExpireYear) == DateTime.Now.Year).WithMessage("The credit card expiry date is invalid.");

Regards,
Michelle
6 years ago
Hi Michelle,

Firstly, I'd like to thank you for sharing this solution (even over 3.5 year later) :)

When i used your snippet code in my project then it didn't worked that i expected.
So i decided to some make changes in your code

Here is the new status of code:



            RuleFor(p => p.ExpireYear)
                .NotEmpty() // Instead of string.IsNullOrEmpty()
                .WithMessage("Credit card expiry year is required")
                .Must(x => Convert.ToInt32(x) >= DateTime.Now.Year)
                //.When(f => !string.IsNullOrEmpty(f.ExpireYear))
                .WithMessage("The credit card expiry year is invalid");

            RuleFor(p => p.ExpireMonth)
                .NotEmpty()
                .WithMessage("Credit card expiry month is required")
                .Must(x => Convert.ToInt32(x) >= DateTime.Now.Month)
                .WithMessage("The credit card expiry month is invalid")
                .When(f => Convert.ToInt32(f.ExpireYear) == DateTime.Now.Year);




Abdurrahman
5 years ago
Thank you Michelle and Abdurrahman!

This solution saved me time for sure.
5 years ago
Thanks so much Michelle!! Your solution worked perfectly for me, it really helped me out!!
This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.