有没有人知道ASP.Net MVC 4上的CreditCardAttribute
类是否阻止了交换卡的验证?
在我的视图模型中,我将其设置为:
[CreditCard]
[Required]
[Display(Name = "Card Number")]
public string CardNumber { get; set; }
我已经使用Visa和Mastercard进行过测试,但是在输入Switch卡时,它不允许通过。
答案 0 :(得分:5)
我有类似的问题,所以我做了验证,并允许我的支付提供商为我验证卡。它的计算成本更高,但内置CreditCardAttribute
似乎相当破碎。我的解决方案:
[Display(Name = "Credit Card Number")]
[Required(ErrorMessage = "required")]
[Range(100000000000, 9999999999999999999, ErrorMessage = "must be between 12 and 19 digits")]
public long CardNumber { get; set; }
这是.NET 4.0 CreditCardAttribute
类代码,您可以调整它以创建自己的信用卡验证属性。你会看到他们做了“mod 10”AKA Luhn Algorithm 的变体,但似乎没有严格遵守它,这可能是Switch无法验证的原因。代码:
[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;
}
}