Validating South African ID Numbers

by Donovan Olivier August 25, 2010 11:56AM

I recently found a nice blog post explaining how to validate South Aftican 13-digit ID numbers, so here's my take on the code:

namespace Imaginary
{
    using System;
    using System.Linq;
    using System.Text;

    public enum Gender
    {
        Unknown,
        Male,
        Female
    }

    public class IdentityInfo
    {
        public IdentityInfo(string identityNumber)
        {
            this.Initialize(identityNumber);
        }

        public string IdentityNumber { get; private set; }

        public DateTime BirthDate { get; private set; }

        public Gender Gender { get; private set; }

        public bool IsSouthAfrican { get; private set; }

        public bool IsValid { get; private set; }

        private void Initialize(string identityNumber)
        {
            this.IdentityNumber = (identityNumber ?? string.Empty).Replace(" ", "");
            if (this.IdentityNumber.Length == 13)
            {
                var digits = new int[13];
                for (int i = 0; i < 13; i++)
                {
                    digits[i] = int.Parse(this.IdentityNumber.Substring(i, 1));
                }
                int control1 = digits.Where((v, i) => i % 2 == 0 && i < 12).Sum();
                string second = string.Empty;
                digits.Where((v, i) => i % 2 != 0 && i < 12).ToList().ForEach(v => 
                                                                 second += v.ToString());
                var string2 = (int.Parse(second) * 2).ToString();
                int control2 = 0;
                for (int i = 0; i < string2.Length; i++)
                {
                    control2 += int.Parse(string2.Substring(i, 1));
                }
                var control = (10 - ((control1 + control2) % 10)) % 10;
                if (digits[12] == control)
                {
                    this.BirthDate = DateTime.ParseExact(this.IdentityNumber
                                                       .Substring(0, 6), "yyMMdd", null);
                    this.Gender = digits[6] < 5 ? Gender.Female : Gender.Male;
                    this.IsSouthAfrican = digits[10] == 0;
                    this.IsValid = true;
                }
            }
        }
    }
}

To use it, simply instantiate a new IdentityInfo, passing in the ID number.


Tags: ,

Blog

The Perpetrator

perpetrator

Donovan Olivier

software developer, architect, husband, father, son, brother, uncle, nephew, sinistral, enquirer, skeptic, cynic, anarchist, contrarian, infidel, dissident, rebel, troublemaker, dissenter, renegade.