Course Content
HTML & JavaScript Interactivity for Beginners
HTML & JavaScript Interactivity for Beginners
Form Validation
Form validation is crucial in web application development as you can't trust the user's input. Therefore, you need to validate the user input both on the server and client side. In this chapter, you'll practice what you have learned in the previous chapter by validating each form element one after the other before submitting the form to the server. Let's get started.
Text Input Validation using onblur
Throughout this chapter, we'll create form elements and check user input each time a user completes the input or while typing. Let's start with the form first.
The above piece of code creates a form element with the action attribute and then returns true or false from the onsubmit
event handler. You'll discover more on this a little later.
Then we'll create an <input>
element where the user has to enter their name.
After that, to make things easier for the user, the code will check if they've entered the input correctly when they move out of the textbox. Below is the JavaScript function that does it.
The above Javascript code creates a regular expression to ensure that the user doesn't enter any numeric values or special characters. Then in the following line, it makes sure that the user doesn't leave the name field empty and that they only enter text by calling the test method (pre-defined method in the javascript library) using the regular expression you created.
If either condition is false, an error message is displayed on the paragraph tag below the name textbox
. Then the focus is set to the textbox
for the user to re-enter and return false.
Else will return true and clear the <error>
tag's contents to ensure all is good.
Email Input Validation
Next, we'll place a textbox
of type email beneath the full name textbox
for the user to enter their email address. Then we'll validate it with the onchange
event handler so that the user knows if they have typed the correct email address or not.
JavaScript code:
The check email function checks the validity of the email address by checking if it's empty and matches the pattern that you've specified in the regular expression. The rest will be the same as that of the name field.
Onsubmit Validation
Then in the onsubmit
event handler, you must ensure that all the fields are filled correctly. If you fill them correctly, it will submit the form to the value specified in the action attribute.The form element is passed as a parameter in this instance.
index
index
index
Now you have an understanding of how form validation works. Likewise, you can validate any form elements using the techniques you've learned here and in the previous chapter.
Thanks for your feedback!