ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

IsValidIranianSocialCode

بررسی اعتبار کد ملی

Source

public static bool IsValidIranianSocialCode( this string codeMelli )
{

    switch ( codeMelli )
    {
        case "1111111111":
        case "2222222222":
        case "3333333333":
        case "4444444444":
        case "5555555555":
        case "6666666666":
        case "7777777777":
        case "8888888888":
        case "9999999999":
        case "0000000000":
        return false;
    }

    long result;
    if ( long.TryParse(codeMelli, out result) )
    {
        switch ( result.NoOfDigits() )
        {
            // because in some cases user ignore the two starting zeros
            case 8:
            long.TryParse((string.Concat("00", result.ToString())), out result);
            return result.CheckValidity();




            // because in some cases user ignore the first starting zero
            case 9:
            long.TryParse((string.Concat("0", result.ToString())), out result);
            return result.CheckValidity();




            case 10:
            return result.CheckValidity();

            default: // below 8 digits is not valid Social No. Code
            return false;



        }
    }
    else return false;

}

public static int NoOfDigits( this long input )
{
    return input.ToString().Length;
}
public static bool CheckValidity( this long socialCode )
{

    char[] splitSocialCode = socialCode.ToString().ToCharArray();
    int sum = 0;
    for ( int i = 0, j = 10; i < 9 & j > 1; sum += int.Parse(splitSocialCode[i++].ToString()) * j-- ) ;
    int reminder = sum % 11;
    if ( reminder < 2 )
        return reminder == int.Parse(splitSocialCode[9].ToString()); // controlling digit
    else
        return (11 - reminder) == int.Parse(splitSocialCode[9].ToString());

}

Example

Console.WriteLine("2300060647".IsValidIranianSocialCode()); // true
Console.WriteLine("2300060648".IsValidIranianSocialCode()); //false
Console.WriteLine("2222222222".IsValidIranianSocialCode()); //false

Author: محمد مهدوی منش 09120611300

Submitted on: 14 jan. 2017

Language: C#

Type: System.String

Views: 3274