Validate integer in form field

Practice that shows how to validate a form field with Javascript to know for sure that its value is an integer.

This practice shows you a simple example of validating an integer with Javascript in a form field. There could be different ways to achieve it, we will show you some of them, so that you can make your own validations.

Suppose we have a form field where we want an integer numerical value to always appear. An example could be a field where we want to store the number of a year, where, logically, neither decimals nor letters fit.

In this exercise we are going to write a script that tries to get an integer of the value that the user has typed in a text field. If it is an integer or can be converted to an integer, it places that integer value in the field. If it can’t get an integer numeric value, it clears the field content and leaves it empty. We will do it with Javascript, since it is the most widespread language on the client side -to operate in the browser.

Integer validation function in Javascript ES6

From Javascript in its ES6 version (ECMAScript 2015) we have a function called Number.isInteger() that allows us to validate an integer. Therefore, this function can be used in all browsers except Internet Explorer.

let number = 22; if(Number.isInteger(number)) { console.log(‘Variable is integer’); }

But be careful: Number.isInteger() does not work with strings, it will only validate you correctly if what you have in the variable you are trying to validate is of type “Number”. If you try to validate a form field, you may not get the expected result, because what is always written in a form field is text, which is not the same as a number.

What you will have to do in the case that the data comes from a form, is to first convert it into an integer.

See also  ASP.NET MVC Framework Manual

This function would do the job you want. Returns true or false depending on whether there is an integer in the field. If there was something that could be understood as an integer, it is responsible for updating the form field to convert it to a true integer (for example, if there is ’33a’, it will change the value of the field to show ’33’. It receives the identifier of the field that you want to validate.

function validateIntegerInField(identificadorDelCampo) { let field = document.getElementById(identificadorDelCampo); let valueInt = parseInt(field.value); if (!Number.isInteger(valueInt)) { return false; } else { field.value = valueInt; return true; } }

I’m sure with a little adaptation on your part you can reuse this function in your own problem.

Classic practice with parseInt() and isNan()

This exercise that we are going to see next is more complete (because we will see an entire form and its validation) and more classic (because it uses more traditional Javascript functions and access to the DOM available in very old browsers). It is also used to learn how to handle Javascript’s built-in parseInt() and isNaN() functions. The first is used to convert a value to an integer and the second to see if a data is a numeric value. The two can be known in depth in the .

Another important topic to know is the browser object hierarchy, but in this case we will make an effort to explain it for those who do not know it.

function validateInteger()

First we are going to create a function that will do most of the work, since it is in charge of validating if a data is an integer. This function receives a value, which is the data we want to validate, and if it is an integer, it will return it as it is. If it is not, it will try to convert it to an integer and if successful it will return that value. Finally, if the attempt to convert it fails, it will return an empty string.

See also  Handlebar Manual

function validateInteger(value){ //try to convert to integer. //if it was an integer it does not affect it, if it was not it tries to convert value = parseInt(value) //I check if it is a numeric value if (isNaN(value)) { //then (it is not number) I return the value empty string return “” }else{ //Else (If it was a number) I return the value return value } }

Practice of validating an integer in a Form

We see the form that we will need to place the text field. It is a form like any other, the only detail is that we have taken care to name both the form itself and the text field. Later we will use those names to refer to the elements through Javascript.

We also have a button-type form field, which in this case serves to indicate that when it is clicked, the function validateForm() will be called. To indicate this, the onclick attribute of the button field is used and between quotes we can see what we want to be executed, in this case the indicated function.

Validation function: validateForm()

This function extracts the data from the text field and passes it to the function validateInteger(), which will return a value that we will have to put back in the text field. To access the form we use the browser’s object hierarchy, which for those of you who don’t know, is a set of objects that refer to all the elements of the page.

Access to page elements is done starting at the window object, which is the first in the hierarchy. Then it continues through the document object -which saves the entire document- and in our example, we will go down to the form to be able to definitively access the text field, which was where we wanted to go. With this schematic:

See also  404 error with Xampp server

window.document.formul.text

We notice that the names of the form and the field that we have placed in the name attribute of the HTML tags of these elements are used.

All text fields have a value property that is where the text that is written inside is stored. So if we want to access what the text field has written, we will write this:

window.document.formul.text.value

Now that we know all the above we should fully understand the code of the function.

function validateFormulario(){ //we extract the value of the field textoCampo = window.document.formul.texto.value //we validate it as an integer textoCampo = validateInteger(textoCampo) //we put the value back window.document.formul.texto. value = fieldText }

conclusion

By itself, this example may not have been very productive, but it may be a start to start more complex ones. With a little imagination and effort we can make functions that validate other form fields to see if what they contain are texts, if they are long or short enough, validate numbers with decimals, etc. All of this would be done in a similar way as we have seen, adding code to the validateForm() function and perhaps building some additional accessory functions such as validateInteger().

We hope it has been useful and see you in another one.

Loading Facebook Comments ...
Loading Disqus Comments ...