Javascript script that shows working with the onblur event. The validity of a piece of data is checked when leaving the text field where it is written.
Onblur is triggered when the user removes the app’s focus from a page element. The focus of the application is where the cursor is.
If, for example, we are located in a text field and we leave that field, either because we click with the mouse in another field of the form or in an empty area, or because the user has pressed the tabulator button (Tab) that moves the focus to the next element on the page.
If I want, when placed outside a text field, to check that the entered value is correct, I can use onblur and call a function that checks if the data is correct. If it is not correct, I can force the focus of the application to be placed again on the text field and notify the user to change said value.
It can be an interesting way to make sure that a valid value is found in a text field. Although it has some downside, as we will see later.
Let’s start with a simple case, where we just want to check a text field to make sure it’s an integer.
This example follows the guide from the beginning of this article, including a new field to validate.
To solve the issue of the infinite loop, which you may have been able to investigate for yourselves and in which one alert box after another was displayed indefinitely, we have used a variable called warned that contains a true if it has already been warned that the field was wrong and a false if it has not been notified yet.
When the alert box is going to be displayed, it checks whether or not the user has been warned. If it has already been notified, nothing is done, preventing more alert boxes from being displayed. If it had not yet been notified, the alert box is displayed and the focus is placed on the field that was incorrect.
To reset the warned variable to false, so that the next time the value is mistyped the corresponding message is displayed, the setTimeout method is used, which executes the instruction with a delay, in this case 50 milliseconds. Enough so that it doesn't get into an infinite loop.
After all the patches we've had to put in to get this event to behave correctly to fulfill its intended purpose, it may not be worth using for this purpose. We can make use of the onchange event, or check all the fields at once when the user has decided to send it.