HTML form action and onsubmit validations with JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<form onsubmit="return validateTheForm()" method="GET" action="https://mail.google.com/mail/">
<br/>
<input type="text" id="txtInput" value=""/>
<input type="submit" value="search"/>
</form>
<script>
   function validateTheForm(){
      var validation = (document.getElementById('txtInput').value == 'gmail');
      if(!validation){
         alert('Something went wrong...Plese write gmail intext box and click');
         return false;
      }
      return true;
   }
</script>
</body>
</html>

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.

Output

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 −

raja
Published on 09-Sep-2020 13:22:29
Advertisements