Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asp.Net MVC 4 creditcard validator not working for switch

Does anyone know if the CreditCardAttribute Class on ASP.Net MVC 4 stops switch cards from being validated?

In my view model I have it set as:

[CreditCard]
[Required]
[Display(Name = "Card Number")]
public string CardNumber { get; set; }

I've tested with Visa and Mastercard, but when entering a Switch card, it doesn't allow it through.

like image 229
Mark Avatar asked Jan 20 '14 19:01

Mark


1 Answers

I had similar issues, so I forewent the validation of it and allow my payment provider to verify the card for me. It's a little more computationally expensive but the built in CreditCardAttribute seems fairly broken. My solution:

[Display(Name = "Credit Card Number")]
[Required(ErrorMessage = "required")]
[Range(100000000000, 9999999999999999999, ErrorMessage = "must be between 12 and 19 digits")]
public long CardNumber { get; set; }

Here's the .NET 4.0 CreditCardAttribute class code which you could tweak to create your own credit card validation attribute. You'll see that they do a variant of the "mod 10" AKA Luhn Algorithm but don't appear to strictly adhere to it which is likely why Switch fails to validate. The code:

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class CreditCardAttribute : DataTypeAttribute
{
    public CreditCardAttribute() : base(DataType.CreditCard)
    {
        base.ErrorMessage = DataAnnotationsResources.CreditCardAttribute_Invalid;
    }
    public override bool IsValid(object value)
    {
        if (value == null)
        {
            return true;
        }
        string text = value as string;
        if (text == null)
        {
            return false;
        }
        text = text.Replace("-", "");
        text = text.Replace(" ", "");
        int num = 0;
        bool flag = false;
        foreach (char current in text.Reverse<char>())
        {
            if (current < '0' || current > '9')
            {
                return false;
            }
            int i = (int)((current - '0') * (flag ? '\u0002' : '\u0001'));
            flag = !flag;
            while (i > 0)
            {
                num += i % 10;
                i /= 10;
            }
        }
        return num % 10 == 0;
    }
}
like image 103
Haney Avatar answered Sep 28 '22 03:09

Haney