Thursday, July 2, 2015

Israeli ID Validation Attribute in ASP.NET

ID validation code extracted from Code Oasis
From this site, I learned the algorithm is based on the Luhn Algorithm
public class IsraeliIDAttribute : ValidationAttribute
    {
        public override string FormatErrorMessage(string name)
        {
            return base.FormatErrorMessage(name);
        }
 
        public override bool IsValid(object value)
        {
            string id = value as string;
 
            if (!Regex.IsMatch(id, @"^\d{5,9}$"))
                return false;
 
            // number is too short - add leading 0000
            if (id.Length < 9)
            {
                while (id.Length < 9)
                {
                    id = '0' + id;
                }
            }
 
            //validate
            int mone = 0;
            int incNum;
            for (int i = 0; i < 9; i++)
            {
                incNum = Convert.ToInt32(id[i].ToString());
                incNum *= (i % 2) + 1;
                if (incNum > 9)
                    incNum -= 9;
                mone += incNum;
            }
            if (mone % 10 == 0)
                return true;
            else
                return false;
        }
    }
Usage:
public class MyModel
{
    [IsraeliIDAttribute(ErrorMessageResourceName = "InvalidId", ErrorMessageResourceType = typeof(Validations))]
        public String ID { get; set; }
}

1 comment: