Create Contact Form Validation in Javascript | Demo and Tutorial

We already discussed about PHP contact form in the past article. Now we will discuss about how to create contact form validation in Javascript.

You can use this validation part together with PHP contact form. Click the below button to see the demo for PHP contact form with Javascript validation.

Demo For PHP Contact Form with Javascript Validation

Required file:
  • contact_form_js_validation.html

In Javascript there are many validation methods available, here we have used simple method and this will be easily understood by everyone.

Process explanation:

When user click the submit button, the validateForm() Javascript function will be called. Normally the form action page will be executed, but in the form tag we have used the onSubmit attribute in which we have used Javacript function and so it will be called before the redirection of the action page.

The clearAllErrorBlock() function is used to hide the error and success block.

We can get the input value either by Id or Class name, where we have used document.getElementsByClassName function to get the input value. Normally Id is unique of element in the same HTML file, but we can use Class in many elements of the same file.

Using document.getElementById method we will fetch the corresponding element’s value and assign it to the new variable inside validateForm() function.

If the assigned variable is empty, then we need to display the error, this is done by the custom Javascript function showErrorBlock().

The variable error_status inside validateForm() is used to check if any validation issue exists or not. If an error exists, then the page will be retained there and there will be shown error messages in the corresponding field. Otherwise, we will redirect the user into the form action page, but in this example we will just show the success message and the page is retaining there only, if you want the PHP backend process then please see the article PHP contact form.

Full source code of contact_form_js_validation.html

Click the below button to see the demo.
Demo

Please follow and like us:
error

Leave a Reply

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