HTML form action and onsubmit validations with JavaScript?

Let’s see an example wherein we are validating input text onsubmit −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<form onsubmit="return validateTheForm()" method="GET" action="">
<input type="text" id="txtInput" value=""/>
<input type="submit" value="search"/>
   function validateTheForm(){
      var validation = (document.getElementById('txtInput').value == 'gmail');
         alert('Something went wrong...Plese write gmail intext box and click');
         return false;
      return true;

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.


This will produce the following output −

Step 1

Type GMAIL in text box −

After clicking the search button, the output is as follows −

Step 2

On typing another value, except GMAIL, you will get an alert message.

Let’s first type the value and press enter −

After clicking the search button, you will get an alert message as in the below output −

Updated on: 09-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started