javascript code validates a spanish Id

Javascritpt code is able to validate a Spanish ID – National Identity Document. This javascript code validates if the letter attached to the number of the id is the correct one or not.

The code is based on a mathematical algorithm where the entire number of the any given ID is divided by 23 and the remainder of such division will indicate the right letter that a correct ID should have.

In the first part we see a prompt that will collect the information inserted by the user, in this case the number and the letter. That user input is stored in the variable numero.  We establish some requirements on the input, such as the prefix parse, which will convert into an integer – number without decimals – the data inserted.

The data inserted will go through a filter or condition, which is that hte number should not  be greater than 99999999.

If the first part of the condition is met, then another prompt is shown to ask the user to insert the letter of the ID.

mathematical algorithm

The second part of the code is about a mathematical process where a calculation occurs. This calculation is based on obtaining the remainder of dividing the number inserted as ID by the number 23.

As mentioned above the remainder os such division will indicate us the letter that should correspond to the number inserted. The letter is selected from an array of letters in the variable letras.

Finallly, we explain that the correct letter is established by the algorithm according to the remainder of the division and the position of the letter in the array.

For example is the remainder of the division is 0, then the correct letter of the ID should by “T”; which is the position 0 of the “T” in the array. If the remainder of the division is 3, then the correct letter for the ID should be “A”, which is the element 3 in the array letras.

Lastly, the letter entered by the user is compared to the correct letter calculated by the algorithm. If they do not match, a message is displayed indicating that the number and letter inserted are not correct. Otherwise, a message would be displayed validating as correct the information data entered.

This exercise of Javascript validating a Spanish ID is often asked by teachers to Javascript students.

We are a web desin company based in Canarias. This post is an HTML exercise that the students usually encounter in their proyects.