Javascript Submitting Forms

Code Snippets Submitting Forms


In this code snippet, we’ll learn how to submit and validate forms with Javascript.

Form data validation with javascript:

We’ll use the onsubmit attribute to call our validation function when the form is submitted. The function will return a boolean as an indication of whether the validation was successful. This will prevent the form from being sent if the validation fails and false is returned.

Note: This form would be sent via post request to the url/page in action attribute. There is no actual backend code here as this is just to demonstrate form data validation.


<h3>Subscribe To Newsletter</h3>
  onsubmit="return validateEmail()" 
  <input type="text" name="email">
  <input type="submit" value="Subscribe">


function validateEmail(){
	//Get value from form textbox.
	const email = document.forms["newsletterSubscription"]["email"].value;
  //Define regex.
	const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
  //Validate email with regex.    
  	//Inform user.
  	alert("You have successfully subscribed to the newsletter.");
    //Approve submition of form by sending true.
  	return true;
  	//Inform user.
  	alert("Invalid email address provided.");
    //Prevent submission by returning false.
    return false;

Resulting output:

Sending form data with javascript

To send the form data with javascript we first have to prevent it from sending the data. This can be done by subscribing/registering to the submit event. Then we call the preventDefault() function which will prevent the data from being sent. Finally, we can retrieve the values for the form inputs and process them however we want(process in code, save or send to the backend). 


<h3>Subscribe To Newsletter</h3>
<form id="newsletterForm">
  <input id="emailInput" type="text">
  <input type="submit" value="Subscribe"/>


Note: I’ll be using jQuery here see this post if you want to learn more about it.
jQuery('#newsletterForm').submit(function(event) {
      //Prevent form submit.
      //Get value from textbox.
      email = jQuery("#emailInput").val();
      //Send to backend with JS.
      sendTobackend("newsletterSubscribtion", email)

function sendTobackend(action, value){
	//This is where you would send the data to your backend API.
  console.log(action + " for " + email)

Resulting output:


Leave a Reply

Your email address will not be published.

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger