003 – Validating a Form – Javascript Noob to Pro

I believe in learning through doing, so what we are going to do is cover a real-world scenario where we are going to validate a form with javascript.

This will be building on skills we learned in previous episodes, so if you haven’t been following along then please give those a watch first.

Validating a Form – Getting Started

So as we can see here we have a basic form with a name, comment and number field. So to validate these fields we are going to:

  • Prevent submission if any of the fields are empty.
  • Count the number of characters in the comment field.
  • Limit the comment field to 140 characters.
  • Limit the number field to integers
  • Limit the number field to between 1 and 10

Validating a Form – Checking If Fields are Empty

So because we are submitting a form instead of just clicking a button, we will need to use another HTML method called “onsubmit”. This goes in the “<form>” element instead because it is the for form you are submitting instead of just clicking a button. Then we will add a function called “validateForm”. Again you can call your function whatever you like, just as long as the function call in the“onsubmit” matches.

So now inside our “validateForm()” function we are going to get the value of the name field and log it to the console. Now the issue we will come across here is that when we submit the form it will refresh the page and we won’t see the console log. So in order to fix this, we will use “event.preventDefault()”. In order to get the event though it needs to be passed from the function that is calling validateForm by adding “event” to the “()” like so “validateForm(event)”. We also need to return false after the “event.preventDefault()”.

So now if you click submit then it will log the output of the name field to the console.

Adding an “IF” statement

So obviously we only want to prevent the form from submitting when the field is empty. So we are going to add an IF statement to our code and in order to validate if it is empty we will say “document.getElementById(‘name’).value == ” “. This basically says compare the value of the name field to an empty string and if it passes then return true and use the code inside the curly braces “{}”.

Now you will notice we used double equals “==” instead of single equals “=”. This is because the single equals is used to assign a value to something else. The double equals is used to compare one thing to another.

So now the form will only stop submitting if the name field is empty. The issue we have now is that the user has no idea that the form has failed validation because there is no validation error.

So let’s add a “div” tag to hold our error message and if the form fails validation then we will fill that div with some error text if it passes validation then we will reset the error message.

Let’s also make the input field go red in order to catch the users eye. In order to do this, we will create an error class and with our javascript we will assign that class to the name field if the validation fails. If the validation passes though we will remove the class again.


Validating a Form – Counting Characters and Restricting Length

So let’s look at counting some characters. Instead of doing this on submit we will use a new method and use “onkeyup”. The reason we are going to do to it on key up is so we can see the count live, rather than once the form has been submitted.

So we are going to add “onkeyup(countCharacters())” to our comment textarea field and in our javascript “countCharacters()” function we will console log the “.length” value of the comment field.

So obviously we want to output this data to the user so we will add a div to our page and add a 0 inside because the comment field will start off at 0. Then in our JS we are just going to set the innerHTML to change to the length value we got before.

So now we want to restrict the length to 140 characters. In order to do this, we need to detect if the number of characters is more than 140 by using the “>” operator and if it is more than 140 characters we are going to set the value of the field to the value of the field but restricted to 140 characters. We do this by using “.substring(0, 140)”, which essentially says only return everything from position 0 to position 140 in the string.

Validating a Form – Validating an Integer and Validating 1-10

So on our number field, we could have used the HTML number field, but where is the fun in that!. We want to force the number field to only show an integer and we want to make sure that integer is between 1 and 10.

In order to do this, we are going to add an “onkeyup” method to our number field and we will call “validateNumberField()”. We are going to grab the value of the input field and use “parseInt()” to force the value to be an integer.

We are also going to demonstrate how to target an element by its class rather than by its id. We do this by using “document.getElementsByClassName()[0]”. The purpose of the “[0]” is to select which one you want. Because counting starts at 0 in programming we are essentially saying get the first element with that class name.

So what is going on here is we are setting the value of the number field to the value of the number field but passed through “parseInt()” to force the string to be an integer.

Validating 1-10

So we are going to do this one with the “onsubmit method instead. So just like we did before with checking if the form element is empty we are going to add an error div and in the javascript we are going to check if the number is between 1 and 10 and if not then we will throw an error and make the box red.



Conclusion

So now we have some basic validation on our form. However, our code has a lot of repetition in it and isn’t as tidy as it could be. So in the next episode, we are going to look at tidying everything up and we will look at some new concepts in the process.

[source]

003 JavaScript Noob to Pro Source

You may also like...

2 Responses

  1. Paul McGowan says:

    A Little confused as you originally declared a function validateNumberField() but seem to have moved it within the validateForm() function as an if statement, or is that just me being slow!

  2. SIKANDDAR ALI says:

    its looking so difficult but useful

Leave a Reply

Your email address will not be published. Required fields are marked *