Search This Blog

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; }
}

10 comments:

  1. Great Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.
    python Training institute in Pune
    python Training institute in Chennai
    python Training institute in Bangalore

    ReplyDelete
  2. This comment has been removed by the author.

    ReplyDelete
  3. This post is so interactive and informative.keep update more information...
    Android Training in Tambaram
    Android Training in Chennai

    ReplyDelete
  4. Great post. keep sharing such a worthy information.
    Data Science Course in Chennai

    ReplyDelete