Thursday, October 15, 2020

JavaScript Forms


Quite regularly, you meet a website where users enter information into a form before sending it to the server, for example, the account registration form. The information that the user enters into the form needs to be validated to ensure data rationality. 
Some examples of authentication:

  • Check to ensure that the data is not empty.
  • Check email format
  • Check telephone number format

There are basically 3 ways for data validation:

  1. form data will be sent to the server, and validation will be done on the server side.
  2. form data will be validated on the client side by using Javascript, which helps server not have to work too much and increase performance for the application.
  3. Use both above methods to validate form.

 

1- Form Validation

JavaScript provides facility to validate the form on the client-side so data processing will be faster than server-side validation. Most of the web developers prefer JavaScript form validation. Through JavaScript, we can validate name, password, email, date, mobile numbers and more fields.

Form validation generally performs two functions.

  • Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
  • Data Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.

In this topic, I will discuss using Javascript to validate form. Below is the illustration of the program's behavior when the user clicks the Submit button. 

1.   You have to register a function in combination with the onsubmit event of form. The duty of this function is to check the data which a user has entered in form, and return true if all the information entered by the user is valid and vice versa return false.

2.    When the user clicks Submit, the function in combination with the onsubmit event will be called.

3.   If the function in combination with the onsubmit event  returns true, the data of form will be sent to the server and vice versa the Submit action will be canceled.

 

2- Simple Example

OK, this is a simple example helping you understand the operating rules of  Form before practicing more complex examples.

The action attribute of  <form> is used to specify the page to which data will be given or  in other words, this is the page that will process the data sent from the <form> of the current page.  

The pages processing the data sent from form are usually written by Servlet/JSP, PHP technology or technology on the Server-side instead of an HTML page. However, here I do not mention data processing on the server-side in this topic.  

simple-validation-example.html

<!DOCTYPE html>

<html>
  <head>
    <title>Hello Javascript</title>

    <script type="text/javascript">
      function validateForm() {
        var u = document.getElementById("username").value;
        var p = document.getElementById("password").value;

        if (u == "") {
          alert("Please enter your Username");
          return false;
        }

        if (p == "") {
          alert("Please enter you Password");
          return false;
        }

        alert("All datas are valid!, send it to the server!");
        return true;
      }
    </script>
  </head>

  <body>
    <h2>Enter your Username and Password</h2>

    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        method="GET"
        action="process-action.html"
        onsubmit="return validateForm()" >
        Username: <input type="text" name="username" id="username" />
        <br /><br />
        Password: <input type="password" name="password" id="password" />
        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>

process-action.html

 <!DOCTYPE html>

<html>
  <head>
    <title>Process Action</title>
  </head>
  <body>
    <h3>Process Action Page</h3>
    OK, I got data!
    <br /><br />
    <a href="javascript:history.back();">[Go Back]</a>
  </body>
</html>

Output

 



3- Access the form data

·         Access field data through the field ID 

<input type="text" id="username" />
<input type="password" id="password" />

// Access field via ID: 
var uInput = document.getElementById("username"); 
var uValue= uInput.value;

 

·         Access Form fields through the name attribute:


<form name="myForm" ...>
  <input type="text" name="username" />
  <input type="password" name="password" />
  <button type="submit">Submit</button>
</form>

  // Get form via form name:
  var myForm = document.forms["myForm"];
  var u = myForm["username"].value;
  var p = myForm["password"].value;

 

When a user enters inaccurate data on a form field, you should notify the user and focus on that field. 

validation-example1.html 


<!DOCTYPE html>
<html>
  <head>
    <title>Validation</title>
    <script type="text/javascript">
      function validateForm() {
        // Get form via form name:

        var myForm = document.forms["myForm"];
        var u = myForm["username"].value;
        var p = myForm["password"].value;

        if (u == "") {
          alert("Please enter your Username");
          myForm["username"].focus(); // Focus
          return false;
        }

        if (p == "") {
          alert("Please enter you Password");
          myForm["password"].focus(); // Focus
          return false;
        }

        alert("All datas are valid!, send it to the server!");
        return true;
      }
    </script>
  </head>
  <body>
    <h2>Enter your Username and Password</h2>

    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        name="myForm"
        method="GET"
        action="process-action.html"
        onsubmit="return validateForm()"  >
        Username: <input type="text" name="username" />
        <br /><br />

        Password: <input type="password" name="password" />
        <br /><br />

        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>

 

Example-2

Ask a user to enter a number between 0 and 10. 

validation-number-example.html

<!DOCTYPE html>

<html>
  <head>
    <title>Validation</title>

    <script type="text/javascript">
      function validateForm() {
        var myField = document.getElementById("myNumber");

        var value = myField.value;

        if (value == "" || isNaN(value) || value < 0 || value > 10) {
          alert("Invalid input!");
          myField.focus();
          return false;
        }
        return true;
      }
    </script>
  </head>

  <body>
    <h2>Enter a Number between 0 and 10</h2>

    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        name="myForm"
        action="process-action.html"
        onsubmit="return validateForm()"  >
        Number: <input type="text" id="myNumber" />
        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>


 

4- Submit through Javascript

Clicking  <button type="submit"> or  <input type="submit"> inside  form helps you to send the data of this  form to the server, however, you can also do it through  Javascript. 

javascript-submit-example.html 


<!DOCTYPE html>
<html>
  <head>
    <title>Javascript Submit</title>
    <script type="text/javascript">
      function validateForm() {
        var name = document.forms["myForm"]["fullName"].value;

        if (name == "") {
          alert("Please enter your name");
          return false;
        }
        return true;
      }

      function submitByJavascript() {
        var valid = validateForm();

        if (!valid) {
          return;
        }

        var myForm = document.forms["myForm"];
        myForm.submit();
      }
    </script>
  </head>
  <body>
    <h2>Submit a from with Javascript</h2>
    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        name="myForm"
        action="process-action.html"
        onsubmit="return validateForm()" >
        Your Name: <input type="text" name="fullName" value="" />
        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
    <br />
    <!-- A Button outside the form -->
    Button outside the form:

    <button onclick="submitByJavascript()">Click Me to submit form</button>
  </body>
</html>

 

5- Validate automatically

The browser can automatically validate several types of data on the form, such as adding a required attribute to a form field to tell the browser that this field is mandatory. The browser will automatically check and notify an user if an user does not enter that field. 

Note: Too old browsers such as IE version 9 or older does not support automatic validation.

required-example.html 


<!DOCTYPE html>
<html>
  <head>
    <title>Required</title>
  </head>
  <body>
    <h2>Required attribute</h2>
    <div style="border: 1px solid #ddd; padding: 5px">
      <form
        name="myForm"
        action="process-action.html"
        onsubmit="return validateForm()"   >
        Your Name: <input type="text" name="fullName" value="" required />
        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>



Pattern Validation [Example-1]

attr-pattern-example.html

<!DOCTYPE html>

<html>
  <head>
    <title>pattern attribute</title>
  </head>
  <body>
    <h2>Attribute: pattern</h2>
    <div style="border: 1px solid #ddd; padding: 5px">
      <form name="myForm" action="process-action.html">
        Country code:
        <input
          type="text"
          name="countryCode"
          pattern="[A-Za-z]{2}"
          title="Two letter country code" />

        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>



Pattern Validation [Example-2]

Ask an user to enter a password having at least 8 characters.

attr-pattern-example2.html 


<!DOCTYPE html>
<html>
  <head>
    <title>pattern attribute</title>
  </head>
  <body>
    <h2>Attribute: pattern</h2>
    <div style="border: 1px solid #ddd; padding: 5px">
      <form name="myForm" action="process-action.html">
        Password:
        <input
          type="password"
          name="password"
          pattern=".{8,}"
          title="8 or more characters"  />

        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>



Password Pattern Validation 

Ask an user to enter a strong password, having at least 8 characters, at least one uppercase, and at least one lowercase. 

attr-pattern-password-example.html 


<!DOCTYPE html>
<html>
  <head>
    <title>pattern attribute</title>
  </head>
  <body>
    <h2>Attribute: pattern</h2>
    Password must contain 8 or more characters that are of at least 
one number,and one uppercase and lowercase letter:
    <br /><br />
    <div style="border: 1px solid #ddd; padding: 5px">
      <form name="myForm" action="process-action.html">
        Password:
        <input
          type="password"
          name="password"
          pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}"
          title="Invalid password!"   />

        <br /><br />
        <button type="submit">Submit</button>
      </form>
    </div>
  </body>
</html>

Email Pattern Validation 

Ask a user to enter an email address, use the pattern attribute to ensure that the user enters an email in the correct format. 

attr-pattern-email-example.html 


<!DOCTYPE html>
<html>
   <head>
      <title>pattern attribute</title>
   </head>
   <body>
      <h2>Attribute: pattern</h2>
      <div style="border:1px solid #ddd; padding: 5px;">
         <form name="myForm" action="process-action.html">
            Email:
            <input type="password" name = "password"
              pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$"
              title="Invalid password!"/>
            <br/><br/>
            <button type="submit">Submit</button>
         </form>
      </div>
   </body>
</html>