Validate Turkish ID Number with jQuery Validation Plugin

What is jQuery Validation Plugin?

The jQuery Validation Plugin provides drop-in validation for your existing forms, while making all kinds of customizations to fit your application really easy.

This jQuery plugin offers a lot of customization options while simplifying simple client-side form validation. It’s a good choice if you’re creating something new from scratch, but trying to integrate something with lots of existing markups into an existing app. The plugin provides an API for writing your own methods, while it comes with a number of useful verification methods, including URL and email verification. All the bundled methods are translated into English default error messages and 37 other languages.

What is missing?

An additional method that validates Turkish identification numbers (aka T.C. Kimlik No). The plugin is really widely used on Turkish websites and provides out of the box validations for many necessary types. But this one important validation is missing for Turkish developers. The moment I realised, I have developed an extension and raised a pull request to the maintained of this plugin.

Unfortunately, my efforts to improve this jQuery plugin was not appreciated 🙁

Maintainer replied, “As we dont yet support citizen numbers for other countries I am not willing to merge this.“. Although they already have a few non-core validators in their additional folder, mine was not accepted. By “a few”, I meant not 1, not 2, but 48 additional scripts!!! Mine was not worthy enough to merge… 🙁

Validation of Turkish ID Number

It is quite simple after including my additional method js along with jquery-validation plugin.

/*
 * Returns true, if the value is a well formatted turkish identification number (T.C. Kimlik No).
 *
 * Better to use with minlength, maxlength, digits.
 *
 * Example: tcnoInputName: {minlength: 11, maxlength: 11, digits: true, idTR: true}
 *
 */
$.validator.addMethod("idTR", function(value, element) {
    var d = value.split(""), t = 0, e = 0, o = 0, i, n;
    for (i = 0; i < 9; i++) {
        n = parseInt(d[i], 10);
        t += n;
        if (i % 2 === 1) {
            e += n;
        } else {
            o += n;
        }
    }
    return this.optional(element) || !(!/^[1-9][0-9]{10}$/.test(value) || ( (t + parseInt(d[9], 10)) % 10 !== d[10]) || (o * 7 - e) % 10 !== d[9]);
}, $.validator.messages.remote);

Include this file after jQuery and jQuery-validation but before your validation logic.

$('formName').validate({
    rules : {
        inputName : { idTR : true }
    }
});

You can use it simply by stating that the input under the form should return true for “idTR”.

I hope you will find this information useful. If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter or Facebook. Thank you!