asp .net c# luhn algorithm validation mod10 with realtime clientside Javascript

After quickly looking over many different mod10 validation scripts on the web, I decided to create my own. 🙂

The Luhn algorithm, sometimes also referred to as mod10 is actually very simple to do and I recommend first trying it by hand to make sure you fully understand it. The wiki article covers it pretty well.

Once you understand, you might be considering the best way to implement it in a realtime clientside validation scenario. If you’re lucky enough to be using .net, then the solution below should work perfect for you.

Pop the function call into your page load and pass in the id of the textbox which will contain the cc and you’re good to go. Keep in mind if you’re using AJAX you need to register the javascript function with
ScriptManager instead of ClientScript or it will stop working after postback.

(C#)

protected void Page_Load(object sender, EventArgs e)
        {
CreateLuhnJavascriptValidator(tbCC.ClientID);
}
private void CreateLuhnJavascriptValidator(string id)
        {
            WebControl validator = null;

            string js= "function LuhnValidate(sender, args) {var ctlcc = document.getElementById('ctlcard_accountnumber'); var m=0; var cc = ctlcc.value; for(i=0; i<cc.length; i=i+1) { var c = cc.charAt(i); if (i%2==0) { var a=(2*parseInt(c)); if (a>=10) {a=parseInt(a%10)+parseInt(a/10);} m=a+m;}else {m=m+parseInt(c);} /*alert(m);*/} if ((m%10)==0) {args.IsValid=true;} else {args.IsValid=false;} }";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "LuhnValidate", js, true);

            validator = new CustomValidator();
            ((CustomValidator)validator).ControlToValidate = id; //id of control on clientside not serverside
            ((CustomValidator)validator).ErrorMessage = "*mod10";
            ((CustomValidator)validator).ClientValidationFunction = "LuhnValidate";
((CustomValidator)validator).ServerValidate += new ServerValidateEventHandler(ServerLuhnValidator);

            pnlSomePanel.Controls.Add(validator); //alternatively you can also simply place custom validator in your page next to the textbox. placement in a panel or on design side of aspx next to textbox only affects appearance of error message
        }

Pure algorithm (js)

//.net version reqires args and sender to wire up correctly
function dotnetwireup(sender, args) {
args.IsValid=LuhnValidate();
}

function LuhnValidate() {
var ctlcc = document.getElementById('ctlcard_accountnumber'); 
var m=0; 
var cc = ctlcc.value; 
for(i=0; i<cc.length; i=i+1) 
{ 
var c = cc.charAt(i); 
if (i%2==0) 
{ 
var a=(2*parseInt(c)); 
if (a>=10) 
{
a=parseInt(a%10)+parseInt(a/10);
} 
m=a+m;
}
else 
{
m=m+parseInt(c);
} /*alert(m);*/
} if ((m%10)==0) {
return true;
} else {
return false;
}
}

(C#)

 private void ServerLuhnValidator(object sender, ServerValidateEventArgs e)
        {
            try
            {
                e.IsValid = LuhnValidate(e.Value);
            }
            catch (Exception ex)
            {
                //handle error
            }
        }

        private bool LuhnValidate(string cc)
        {
            int m = 0;
            for (int i = 0; i < cc.Length; i++)
            {
                char c = cc.ToCharArray()[i];
                if (i % 2 == 0)
                {
                    int a = 2 * Convert.ToInt32(c.ToString());
                    if (a >= 10)
                    {
                        a = Convert.ToInt32(a % 10) + Convert.ToInt32(a / 10);
                    }
                    m = a + m;
                }
                else
                {
                    m = m + Convert.ToInt32(c.ToString());
                }
            }
            if (m % 10 == 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

References
Wikipedia, http://en.wikipedia.org/wiki/Luhn_algorithm

Advertisement

About Ronnie Diaz

Ronnie Diaz is a software engineer and tech consultant. Ronnie started his career in front-end and back-end development for companies in ecommerce, service industries and remote education. This work transitioned from traditional desktop client-server applications through early cloud development. Software included human resource management and service technician workflows, online retail e-commerce and electronic ordering and fulfillment, IVR customer relational systems, and video streaming remote learning SCORM web applications. Hands on server experience and software performance optimization led to creation of a startup business focused on collocated data center services and continued experience with video streaming hardware and software. This led to a career in Amazon Prime Video where Ronnie is currently employed, building software and systems which stream live sports and events for millions of viewers around the world.

Posted on November 1, 2011, in Programming & Development and tagged , , , , , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: