Javascript Submitting Forms

Code Snippets Submitting Forms
Share:

About

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.

HTML

<h3>Subscribe To Newsletter</h3>
<form 
  name="newsletterSubscription" 
  action="/subscribeNewsletter.php" 
  onsubmit="return validateEmail()" 
  method="post"
>
  <input type="text" name="email">
  <input type="submit" value="Subscribe">
</form>

Javscript

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.    
	if(regex.test(String(email).toLowerCase())){
  	//Inform user.
  	alert("You have successfully subscribed to the newsletter.");
    //Approve submition of form by sending true.
  	return true;
  }
  else{
  	//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). 

HTML

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

Javscript

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.
      event.preventDefault(); 
      //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:

Share:

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