Form Validation using JavaScript

Samanja Cartagena
3 min readNov 5, 2022

The old fashioned way like a neantherdal


At first create a form with HTML

This form would look something like this.

Now, I have added the required validation keyword in the input fields which means that the form cannot be submitted if the input fields are empty. By specifying the type in the input fields, we are making sure that the right type is being entered as an input for example, if we try to enter an incorrect email address without the @ the input field would give an error and the form would refuse to get submitted.

Now to finally add some conditions to the password input field. What if we want the password to be greater than 6 digits. What do we do than? At first we add something to the submit button that would trigger a function. This function would prevent the form from being submitted unless the password length is less than 6 digits.

Here, we have added the built in onclick method that triggers the checkPassword function. This checkPassword function would be built inside the script tags because it will be pure JavaScript. This is what it would look like

Here, we have created a function that checks to see if the password inputted by the password field is less than 6 digits.

A variable called pass is created. This variable takes in the value of password input field. As you can see I have named the form ‘myForm’ and the password field ‘password’. Now we can test the value of the input field to see if the length of the variable pass is less than 6 or not. If pass is less than 6 digits an alert is triggered. Than, I am using addEventListener to prevent the default function of the submit button. The event.preventDefault() prevents the default submission of form. Hence the submission of this form is halted if the password length is less than 6. Than next we want to clear out the input values of the form. With document.forms[‘myForm’][‘email’].value =””. We are making the email input field empty and the password input field empty again.

I hope, you enjoyed reading it, this was my first project on form validation in college. I remember I was over the moon when it worked.

You are free!!

Spread the love like a spread operator