使用ASP.NET MVC进行VIN编号验证

5 c# asp.net validation asp.net-mvc asp.net-mvc-4

我正在使用MVC 4进行当前项目.项目通常涉及车辆并识别不同用途的正确车辆.

我有以下型号.

public class Vehicle
{
   [Required]
   public string VIN{get; set;}
   //
}
Run Code Online (Sandbox Code Playgroud)

我想验证正确的传入VIN号码.我不确定验证类似VIN号码的正确/最简单方法是什么.我看过一些验证示例,似乎没有一个对我有用.在客户端验证方面需要一些帮助.谢谢.

Lin*_*Lin 9

我正在使用RegularExpression在我自己的项目中验证VIN.试试下面的例子:

public class Vehicle
{
    [RegularExpression("[A-HJ-NPR-Z0-9]{13}[0-9]{4}", ErrorMessage = "Invalid Vehicle Identification Number Format.")]
    public string VIN { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

VIN通常由17个字符组成.

VIN的第一个字母或数字告诉您您的车辆在世界的哪个区域制造.

第二个字母或数字与VIN中的第一个字母或数字相结合,可以告诉您汽车或卡车在哪个国家/地区制造.

车辆制造商使用第三个数字或字母来识别它是什么类型的车辆.

第4个5月6日,第7个第8个字符,你可以找到车型,发动机类型,车身风格.

第9个字符是VIN校验位,您可以使用数学来确定它是否是正确的VIN.

VIN的第10个字母或数字告诉您车辆的车型年份.

11月12日13日14日15日第16个字符是汽车制造商输入有关VIN所属特定车辆的独特信息的地方.

希望能帮助到你!


Eon*_*dan 5

这是@hardknocks 在 C# 中的答案

public static bool ValidateVin(string vin)
{
    if (vin.Length != 17)
        return false;
    var result = 0;
    var index = 0;
    var checkDigit = 0;
    var checkSum = 0;
    var weight = 0;
    foreach (var c in vin.ToCharArray())
    {
        index++;
        var character = c.ToString().ToLower();
        if (char.IsNumber(c))
            result = int.Parse(character);
        else
        {
            switch (character)
            {
                case "a":
                case "j":
                    result = 1;
                    break;
                case "b":
                case "k":
                case "s":
                    result = 2;
                    break;
                case "c":
                case "l":
                case "t":
                    result = 3;
                    break;
                case "d":
                case "m":
                case "u":
                    result = 4;
                    break;
                case "e":
                case "n":
                case "v":
                    result = 5;
                    break;
                case "f":
                case "w":
                    result = 6;
                    break;
                case "g":
                case "p":
                case "x":
                    result = 7;
                    break;
                case "h":
                case "y":
                    result = 8;
                    break;
                case "r":
                case "z":
                    result = 9;
                    break;
            }
        }

        if (index >= 1 && index <= 7 || index == 9)
            weight = 9 - index;
        else if (index == 8)
            weight = 10;
        else if (index >= 10 && index <= 17)
            weight = 19 - index;
        if (index == 9)
            checkDigit = character == "x" ? 10 : result;
        checkSum += (result * weight);
    }

    return checkSum % 11 == checkDigit;
}
Run Code Online (Sandbox Code Playgroud)