Many times when dealing with forms, we want to stop the form from submitting on its own and grab the form fields so we can do some validation. Suppose we have the following form code…
Notice the span tag? It is empty. We can perform validation and show any errors to the end user utilizing the span tag. How?
We grab our form from the DOM…
We add our submit event listener…
Here we are grabbing the span tag, putting text in it and formatting it with a red color. We are also making the border of the form field red and putting the cursor in the field with the focus method.
Now typically, we would wrap this code in some sort of if statement where we are checking whether the data is correct or not. We can check the length, content, etc. We can even use regular expressions to test the input data. An example might be…