其中算法并CreditCardAttribute使用信用卡号码格式验证 [英] Which algorithm does CreditCardAttribute use for credit card number format validation

查看:408
本文介绍了其中算法并CreditCardAttribute使用信用卡号码格式验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.NET 4.5包含名为<一个新的验证属性href="http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.creditcardattribute.aspx"相对=nofollow> CreditCardAttribute 和该属性指定数据字段的值是一个信用卡号码。当我反编译,其中包含这个类的程序集,我可以看到下面的code的信用卡号码验证:

 公众覆盖布尔的IsValid(对象的值)
{
  如果(价值== NULL)
  {
    返回true;
  }
  字符串文本=值串;
  如果(文字== NULL)
  {
    返回false;
  }
  文本= text.Replace( - ,);
  文本= text.Replace(,);
  INT NUM = 0;
  布尔标志= FALSE;
  的foreach(炭电流text.Reverse&LT;焦炭&GT;())
  {
    如果(电流I'0'||当前&GT;'9')
    {
      返回false;
    }
    INT I =(int)的((电流 - '0')*(标志'\ u0002':'\ U0001'));
    标志=标志!;
    而(ⅰ大于0)
    {
      NUM + = I%10;
      的i / = 10;
    }
  }
  返回NUM%10 == 0;
}
 

有谁知道它的算法在这里应用来验证数字格式?卢恩的算法?此外,这是ISO标准?最后,你认为这是正确的,并100%正确实施?

MSDN不提供有关此多的信息。事实上,他们有错误的信息,如下:

  

说明

     

该值是使用常规EX pression验证。类不   验证信用卡号是有效的购买,只   它是完全形成了。

解决方案

最后一行:

 返回NUM%10 == 0;
 

是一个非常强大的暗示,这是一个卢恩算法

.NET 4.5 includes a new validation attribute named as CreditCardAttribute and this attribute specifies that a data field value is a credit card number. When I decompile the assembly which contains this class, I can see the following code for the credit card number validation:

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;
}

Does anybody know which algorithm is applied here to validate the number format? Luhn's algorithm? Also, is this an ISO standard? Finally, do you think that this is the right and 100% correct implementation?

MSDN doesn't provide much information about this. In fact, they have the wrong information as below:

Remarks

The value is validated using a regular expression. The class does not validate that the credit card number is valid for purchases, only that it is well formed.

解决方案

The last line:

return num % 10 == 0;

Is a very strong hint that this is a Luhn Algorithm

这篇关于其中算法并CreditCardAttribute使用信用卡号码格式验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆