Creating a basic textbox
Note that the script tags are empty, i.e., they do not have any code in between them. Outside of the script tags (but inside the body tags) we have a form. The form has an id (called “namecheck”). The form is composed of a H2 element prompting the user to enter their name. Then it has a textbox input field. The “input” tag specifies the type (in this case, “text”) and the name of the variable that will store what the user types into it (in this case, “username”).
(Usually these forms will also have a submit button but we will forgo that for now since we are aiming to demonstrate how to do input text validation.)
If you try loading this webpage in your browser, it will look like this:
If you now attempt to type some characters into the textbox, like so:
you will see that you are able to enter special characters into the textbox without any validation whatsoever. In the rest of this blog, we will see how to not allow special characters.
Validating textbox user input
First, we will reference a function called “validate()” that will be called everytime the user presses a key in the textbox. This can be accomplished by the following code:
As the code above demonstrates, everytime the user types something (via a key press), the validate() function is called and the results are returned, to be displayed in the textbox. Note that the validate() function takes as input the event that has triggered it. But there is no such function yet - we need to add the definition of this function in between the “script” tags.
Below is some code to validate events as they occur.
Now let us try using our form by typing “Harry Potter”:
Wow - what happened? Note that the space character is not recognized and thus disallowed in the textbox. If we would like to allow space characters, we should update our list of allowed ASCII codes, like so:
Now let us try typing “Harry Potter”:
In this case, the space character is allowed. Continuing in this manner, you can expand (or shrink) the set of allowed characters. For instance, you can add numbers if you would like to allow them.
If you liked learning about texxtboxes and validating inputs, checkout our blogpost on gathering user input.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.