Forms in JavaScript
Posted by Superadmin on May 03 2023 02:16:05

Forms in JavaScript

By Priya PedamkarPriya Pedamkar
  

Forms in JavaScript

Introduction to Forms in JavaScript

JavaScript is a programming language used commonly in web-application for calculating, manipulating, and validating data, making dynamic pages, and interacting with the user. Since JavaScript has many use cases, in this article we will be learning about forms and form validation through JavaScript.

With the help of JavaScript, we can enhance, validate the HTML form and its elements on the client-side without even invoking the server. JavaScript can ensure all the requirements are fulfilled by the user before submitting the form to the application program.

Since we can validate the form on the client-side, data-processing becomes faster when compared with server-side validation. Most web developers make use of JavaScript form validation.

Forms in JavaScript 1-1

Form Validation in JavaScript

Forms are an important section of any web application to collect user information, feedback or queries. Through JavaScript, we can provide a better user experience by displaying results to the user in an efficient way.

Elements that are most commonly used in forms to collect data are:

When implementing forms, we must provide a name to our form and the elements we have used in our form because the names that we have assigned helps us to refer those object (form and its element) in our JavaScript.

A typical form looks like the one shown below,

Code:

<INPUT TYPE="text" NAME="fullName" VALUE="">
<INPUT TYPE="button" NAME="submit" Value="Click">
</FORM>
Note: I’ve provided NAME= attributes for all form elements, including the form itself.

JavaScript form makes use of event handlers, such as onClick or onSubmit to invoke a JavaScript action when the user performs an action in the form, like clicking a button.

Example to Collect and Validate User Information in JavaScript

The code implementation to collect and validate user information is given below.

1. index.html

Code:

<html lang="en">
<head>
<meta charset="UTF-8">
<title>JavaScript | User Sign-In Form </title>
<link rel="stylesheet" href="form-style.css">
</head>
<body>
<form name="demoForm" onsubmit="return validateForm()"  method="post">
<h2>Personal Information</h2>
<div class="row">
<label>Full Name</label>
<input type="text" name="name">
<div class="errtext" id="nameErr"></div>
</div>
<div class="row">
<label>Email Address</label>
<input type="text" name="email">
<div class="errtext" id="emailErr"></div>
</div>
<div class="row">
<label>Mobile Number</label>
<input type="text" name="mobile" maxlength="10">
<div class="errtext" id="mobileErr"></div>
</div>
<div class="row">
<label>Password</label>
<input type="password" name="pswd">
<div class="errtext" id="pswdErr"></div>
</div>
<div class="row">
<label>Country</label>
<select name="country">
<option>Select</option>
<option>Amstermdam</option>
<option>India</option>
<option>Mexico</option>
<option>UAE</option>
</select>
<div class="errtext" id="countryErr"></div>
</div>
<div class="row">
<label>Gender</label>
<div class="form-inline">
<label><input type="radio" name="gender" value="male"> Male</label>
<label><input type="radio" name="gender" value="female"> Female</label>
</div>
<div class="errtext" id="genderErr"></div>
</div>
<div class="row">
<label>Hobbies <i>(Optional)</i></label>
<div class="form-inline">
<label><input type="checkbox" name="hobbies[]" value="sports"> Sports</label>
<label><input type="checkbox" name="hobbies[]" value="read"> Reading</label>
<label><input type="checkbox" name="hobbies[]" value="music"> Music</label>
</div>
</div>
<div class="row">
<input type="submit"  value="Register">
</div>
</form>
</body>
<script src="validate.js"></script>
</html>

2. vaidate.js

Code:

function printerrtext(elemId, hintMsg) {
document.getElementById(elemId).innerHTML = hintMsg;
}
// Defining a function to validate form
function validateForm() {
// Retrieving the values of form elements
var name = document.demoForm.name.value;
var email = document.demoForm.email.value;
var mobile = document.demoForm.mobile.value;
var country = document.demoForm.country.value;
var gender = document.demoForm.gender.value;
var pswd = document.demoForm.pswd.value;
var hobbies = [];
var checkboxes = document.getElementsByName("hobbies[]");
for(var i=0; i < checkboxes.length; i++) {
if(checkboxes[i].checked) {
// Populate hobbies array with selected values
hobbies.push(checkboxes[i].value);
}
}
// Defining errtext variables with a default value
var nameErr = emailErr = mobileErr = countryErr = genderErr = pswdErr = true;
// Validate name
if(name == "") {
printerrtext("nameErr", "Please enter your name");
} else {
var regex = /^[a-zA-Z\s]+$/;
if(regex.test(name) === false) {
printerrtext("nameErr", "Please enter a valid name");
} else {
printerrtext("nameErr", "");
nameErr = false;
}
}
// Validate email address
if(email == "") {
printerrtext("emailErr", "Please enter your email address");
} else {
// Regular expression for basic email validation
var regex = /^\S+@\S+\.\S+$/;
if(regex.test(email) === false) {
printerrtext("emailErr", "Please enter a valid email address");
} else{
printerrtext("emailErr", "");
emailErr = false;
}
}
// Validate mobile number
if(mobile == "") {
printerrtext("mobileErr", "Please enter your mobile number");
} else {
var regex = /^[1-9]\d{9}$/;
if(regex.test(mobile) === false) {
printerrtext("mobileErr", "Please enter a valid 10 digit mobile number");
} else{
printerrtext("mobileErr", "");
mobileErr = false;
}
}
// Validate Password
if(pswd == ""){
printerrtext("pswdErr", "Please enter your password");
} else{
var regex = /^(?=.*[0-9])(?=.*[!@#$%^&*])[a-zA-Z0-9!@#$%^&*]{6,16}$/;
if(regex.test(pswd) === false) {
printerrtext("pswdErr", "Min : 6 chacracter in form Asd4$l");
} else{
printerrtext("pswdErr", "");
pswdErr = false;
}
}
// Validate country
if(country == "Select") {
printerrtext("countryErr", "Please select your country");
} else {
printerrtext("countryErr", "");
countryErr = false;
}
// Validate gender
if(gender == "") {
printerrtext("genderErr", "Please select your gender");
} else {
printerrtext("genderErr", "");
genderErr = false;
}
// Prevent the form from being submitted if there are any errtexts
if((nameErr || emailErr || mobileErr || countryErr || genderErr || pswdErr) == true) {
return false;
} else {
// Creating a string from input data for preview
var dataPreview = "You've entered the following details: \n" +
"Full Name: " + name + "\n" +
"Email Address: " + email + "\n" +
"Mobile Number: " + mobile + "\n" +
"Country: " + country + "\n" +
"Gender: " + gender + "\n";
if(hobbies.length) {
dataPreview += "Hobbies: " + hobbies.join(", ");
}
// Display input data in a dialog box before submitting the form
alert(dataPreview);
}
};

3. form-style.css

Code:

font-size: 16px;
background: #f9f9f9;
font-family: "Segoe UI", "Helvetica Neue", Arial, sans-serif;
}
h2 {
text-align: center;
text-decoration: underline;
}
form {
width: 300px;
background: #fff;
padding: 15px 40px 40px;
border: 1px solid #ccc;
margin: 50px auto 0;
border-radius: 5px;
}
label {
display: block;
margin-bottom: 5px
}
label i {
color: #999;
font-size: 80%;
}
input, select {
border: 1px solid #ccc;
padding: 10px;
display: block;
width: 100%;
box-sizing: border-box;
border-radius: 2px;
}
.row {
padding-bottom: 10px;
}
.form-inline {
border: 1px solid #ccc;
padding: 8px 10px 4px;
border-radius: 2px;
}
.form-inline label, .form-inline input {
display: inline-block;
width: auto;
padding-right: 15px;
}
.errtext {
color: red;
font-size: 90%;
}
input[type="submit"] {
font-size: 110%;
font-weight: 100;
background: #006dcc;
border-color: #016BC1;
box-shadow: 0 3px 0 #0165b6;
color: #fff;
margin-top: 10px;
cursor: pointer;
}
input[type="submit"]:hover {
background: #0165b6;
}

Output #1: Correct User Input

Forms in JavaScript 1-2

Output #2: Wrong/Missing User credentials

User credentials

The data entered in the form needs to be in the correct format as required by the application and certain fields need to mandatorily be filled in order to submit the form.

Conclusion – Forms in JavaScript

In this article, we have learned about form and the various elements or controls used in forms and what role JavaScript plays in the form validation, verification of data entered by the user, event-handling functions when an action is performed like clicking a button and its benefits.