Create a simple Web Form with JavaScript validation

Get FREE domain for 1st year and build your brand new site

Free book on Binary Tree

In this article, we have presented step by step instructions to Create a simple Web Form in HTML with JavaScript validation and CSS to make the form presentable.

Table of content:

  1. Introduction to Form + HTML, CSS, JavaScript
  2. Implementing the form in HTML
  3. Add JavaScript to form for validation
  4. Add CSS to make form presentable
  5. Elements of a Web Form

Follow along the steps to create your own form.

Introduction to Form + HTML, CSS, JavaScript

HTML, in combination with CSS and JavaScript, can be used to create forms on websites. A form is basically used in webpages for the user to enter their required details that are sent to the server for processing. Examples of such form use are prevalent in e-commerce websites, online banking, online surveys, etc.

Creating a simple, generic form is a fairly easy task. The example below will show you to create a registration form. With simple tweaks, you can change the fields to whatever will be suitable for you.

In short:

  • HTML is used to create the form.
  • JavaScript to validate the form.
  • CSS to design the layout of the form.

Implementing the form in HTML

In the HTML code, declare the fields which need to be added in the form. In this example, there's name, address, email, password, telephone, course. These basically act as headings, so you can give whatever size, style, weight you want. For courses, create a drop down menu using the option tag. We then have 2 buttons, one to submit the form and the other to reset the fields.

Our first step will be to create the form in HTML code. So we need to declare a title at the top.

<h1 style="text-align: center"> REGISTRATION FORM </h1> 

Capture-16

Then add the form tag to create a form. The action attribute specifies where to send the form-data after submission. When clicked on submit, it will run the javascript to validate the form.

<form name="RegForm" action="/submit.php" onsubmit="return scriptForm()" method="post">

Declare a field in the form followed by a box where the user can provide an answer.

<p>Name: <input type="text" size=65 name="Name"> </p><br>

Capture-17

Similarly, fill up the form with other required fields for the user to fill up.

<p>E-mail Address: <input type="text" size=65 name="EMail">  </p><br> 
<p>Telephone: <input type="text" size=65 name="Telephone"> </p><br>

We can also use radio buttons to allow the user to pick between given choices.

<p>Gender:
    <input type="radio" name="Gender" value="male"> Male
    <input type="radio" name="Gender" value="female"> Female </p><br>

Next, we can create a drop down menu, providing the user with options to select. In this case, we will ask the user to choose the course which they are pursuing.

<p>SELECT YOUR COURSE
    <select type="text" value="" name="Subject"> 
        <option>BTECH</option> 
        <option>BBA</option> 
        <option>BCA</option> 
        <option>BCOM</option> 
    </select>
</p><br><br> 

Finally, we create two buttons, one to submit the form, and the other to reset the fields. Our registration form in pure HTML code will look like this-

<html>
<body> 
<h1 style="text-align: center"> REGISTRATION FORM </h1> 
<form name="RegForm" action="/submit.php" onsubmit="return scriptForm()" method="post">  

    <p>Name: <input type="text" size=65 name="Name"> </p><br> 
    <p>E-mail Address: <input type="text" size=65 name="EMail">  </p><br> 
    <p>Telephone: <input type="text" size=65 name="Telephone"> </p><br> 
    <p>Gender:
        <input type="radio" name="Gender" value="male"> Male
        <input type="radio" name="Gender" value="female"> Female </p><br>

    <p>SELECT YOUR COURSE
        <select type="text" value="" name="Subject"> 
            <option>BTECH</option> 
            <option>BBA</option> 
            <option>BCA</option> 
            <option>BCOM</option> 
        </select></p><br><br> 

    <p><input type="submit" value="Send" name="Submit"> 
        <input type="reset" value="Reset" name="Reset"> 
    </p> 
</form> 
</body>
</html>

Capture-20

Add JavaScript to form for validation

A script will be ran to validate whether the details in the form are entered correctly. For example, upon hitting the submit button, if any of the fields are empty, then the user will be alerted to fill those field up. It can also be used to check whether the phone number consists of digits or whether the email address has the correct domain and @ sign. If there's no issues with any of the fields then the script will return a boolean value of true.

<script> 
function scriptForm() 
{ 
    var name = document.forms["RegForm"]["Name"];               
    var email = document.forms["RegForm"]["EMail"];    
    var phone = document.forms["RegForm"]["Telephone"];  
    var what =  document.forms["RegForm"]["Subject"];  
    var rad = document.forms["RegForm"]["Gender"];

    //checks if name field is empty
    if (name.value == "")                                  
    { 
        window.alert("Please enter your name."); 
        name.focus(); 
        return false; 
    } 

    //checks if email field is empty
    if (email.value == "")                                   
    { 
        window.alert("Please enter a valid e-mail address."); 
        email.focus(); 
        return false; 
    } 

    //checks if email field contains @
    if (email.value.indexOf("@", 0) < 0)                 
    { 
        window.alert("Please enter a valid e-mail address."); 
        email.focus(); 
        return false; 
    } 

    //checks if email field contains .
    if (email.value.indexOf(".", 0) < 0)                 
    { 
        window.alert("Please enter a valid e-mail address."); 
        email.focus(); 
        return false; 
    } 

    //checks if phone field is empty
    if (phone.value == "")                           
    { 
        window.alert("Please enter your telephone number."); 
        phone.focus(); 
        return false; 
    } 

    //checks if any of the radio buttons was selected
    if (rad.selectedIndex == null)                  
    { 
        alert("Please select a gender."); 
        rad.focus(); 
        return false; 
    }

    //checks if any of the courses from drop down menu was selected
    if (what.selectedIndex < 1)                  
    { 
        alert("Please enter your course."); 
        what.focus(); 
        return false; 
    }

    //if everything is filled up/selected then submission will continue without the browser giving any alert dialog boxes
    return true; 
}
</script> 

Capture-21

Add CSS to make form presentable

This is the CSS code which shows how the heading, content and blanks should be positioned. It is inlcuded in the style tag. For this example, it is categorized into three subparts- one for the entire form, one for the heading and one for the boxes.

<style> 
scriptForm { 
    margin-left: 70px; 
    font-weight: bold ; 
    float: left; 
    clear: left; 
    width: 100px; 
    text-align: left; 
    margin-right: 10px; 
    font-family:sans-serif,bold, Arial, Helvetica; 
    font-size:14px; 
} 

div { 
    box-sizing: border-box; 
    width: 100%; 
    border: 100px solid black; 
    float: left; 
    align-content: center; 
    align-items: center; 
} 

form { 
    margin: 0 auto; 
    width: 600px; 
}
</style> 

Here's how the complete form will look like after applying CSS design-

Capture-22

Elements of a Web Form

  1. text - a simple text box that allows input of a single line of text.
  2. email - a type of text that requires a partially validated email address
  3. number - a type of text that requires a number
  4. password - similar to text, it is used for security purposes, in which the characters typed in are invisible or replaced by symbols such as *)
  5. radio - a radio button
  6. file - a file select control for uploading a file
  7. reset - a reset button that, when activated, tells the browser to restore the values to their initial values.
  8. submit - a button that tells the browser to take action on the form (typically to send it to a server)
  9. textarea - much like the text input field except a textarea allows for multiple rows of data to be shown and entered
  10. select - a drop-down list that displays a list of items a user can select from

With this article at OpenGenus, you must have the complete idea of how to develop a simple web form in HTML by using JavaScript for validation of input.