برای بررسی صحت کدملی باید کمی با ساختار این کد آشنا شویم. کد ملی 6-761161-007 را در نظر بگیرید. همانطور که مشاهده میکنید این کد به 3 قسمت تقسیم شده است. قسمت اول که یک عدد 3 رقمی است نشان دهنده محل تولد فرد است. 6 رقم وسط شماره شناسایی فرد و رقم آخر، رقم کنترل است. در حقیقت ساختار 9 رقم اول طبق الگوریتمی قابل بررسی است که خروجی آن الگوریتم همان رقم آخر است. اگر خروجی الگوریتم با رقم کنترل برابر باشد میتوان گفت کدملی وارد شده معتبر است و در غیر اینصورت کدملی معتبر نخواهد بود.پی نوشت:
برای این منظور دو متدالحاقی زیر به پروژه DNT.Extensions اضافه شده است که بدنه آنها به شرح زیر است:
/// <summary> /// Validate IR National Code /// </summary> /// <param name="nationalcode">National Code</param> /// <returns></returns> public static bool IsValidNationalCode(this string nationalcode) { int last; return nationalcode.IsValidNationalCode(out last); } /// <summary> /// Validate IR National Code /// </summary> /// <param name="nationalcode">National Code</param> /// <param name="lastNumber">Last Number Of National Code</param> /// <returns></returns> public static bool IsValidNationalCode(this string nationalcode, out int lastNumber) { lastNumber = -1; if (!nationalcode.IsItNumber()) return false; var array = nationalcode.ToCharArray(); if (array.Length != 10) return false; var j = 10; var sum = 0; for (var i = 0; i < array.Length - 1; i++) { sum += Int32.Parse(array[i].ToString(CultureInfo.InvariantCulture)) * j; j--; } var div = sum / 11; var r = div * 11; var diff = Math.Abs(sum - r); if (diff <= 2) { lastNumber = diff; return diff == Int32.Parse(array[9].ToString(CultureInfo.InvariantCulture)); } var temp = Math.Abs(diff - 11); lastNumber = temp; return temp == Int32.Parse(array[9].ToString(CultureInfo.InvariantCulture)); }
طریقه استفاده از این متدها نیز به شرح ذیل است:
bool b = "0077611616".IsValidNationalCode();
لطفاً بخش نظرات خوانندگان را نیز دنبال کنید.