Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to add form validation for empty input fields with JavaScript?
To add form validation for empty input fields with JavaScript, the code is as follows −
Example
<!DOCTYPE html>
<html>
<head></head>
<h1>JavaScript empty input field validation example</h1>
<form
name="Form1"
onsubmit="return emptyValidation()"
required>
Name: <input type="text" name="firstName" />
<input type="submit" value="Submit" />
</form>
<h2>Submit the form empty to see the validation performed</h2>
<script>
function emptyValidation() {
var formField = document.forms["Form1"]["firstName"].value;
if (formField == "" || x == null) {
alert("Name must be filled out");
return false;
}
}
</script>
</body>
</html>
Output
The above code will produce the following output −

On submitting the form empty −

Advertisements