How to do Form Validation Using JavaScript

Form validation is a crucial aspect of web development.

It helps ensure that the data entered by users is accurate and complete before it is submitted to the server.

With JavaScript, you can easily validate forms on the client-side, providing a better user experience and reducing the load on the server.

In this Javascript tutorial, we will go over the basics of form validation using JavaScript.

We will cover different validation techniques, including the use of regular expressions, and provide code examples to help you get started.


Basic Form Validation

The simplest form of validation is to check if the required fields are filled in.

This can be done using the HTML5 required attribute, which specifies that an input field must be filled in before the form can be submitted.

However, this method has its limitations, as it only checks if the field is filled in, not if the data entered is valid.

For example, if you have a field for an email address, the required attribute will only check if the field is filled in, not if the email address is in the correct format.

JavaScript Validation

To overcome these limitations, we can use JavaScript to validate the form on the client-side.

The basic idea is to check the values of the form fields and display an error message if the data entered is not valid.

One way to do this is to use conditional statements.

For example, to check if an email address is in the correct format, you can use the following code:

function validateForm() {
  var email = document.getElementById("email").value;
  var atpos = email.indexOf("@");
  var dotpos = email.lastIndexOf(".");
  if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length) {
    alert("Not a valid e-mail address");
    return false;
  }
  return true;
}

In this code, we first get the value of the email field using the getElementById method.

Then, we use the indexOf and lastIndexOf methods to find the positions of the @ and . characters in the email address.

If the @ symbol is not in the first position or the . symbol is not after the @ symbol, we display an error message using the alert method and return false to prevent the form from being submitted.

Regular Expressions

Another way to validate form data is to use regular expressions.

Regular expressions are patterns that can be used to match strings.

They are very useful for checking if a string matches a specific format, such as an email address or a phone number.

For example, to check if an email address is in the correct format, you can use the following code:

function validateForm() {
  var email = document.getElementById("email").value;
  var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  if (!pattern.test(email)) {
    alert("Not a valid e-mail address");
    return false;
  }
  return true;
}

In this code, we first define a pattern using the regular expression `/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/`.

The pattern specifies that the email address must start with one or more characters that are either letters, numbers, dots, underscores, or hyphens, followed by the @ symbol, then one or more characters that are either letters, numbers, dots, or hyphens, followed by a dot, and finally two to four letters.

We then use the test method to check if the email address matches the pattern.

If it does not match, we display an error message and return false to prevent the form from being submitted.

Displaying Error Messages

To provide a better user experience, it is recommended to display error messages next to the form fields instead of using the alert method.

This can be done using HTML elements, such as <span> or <p>, and JavaScript to dynamically change their content and style.

For example, to display an error message next to the email field, you can use the following code:

function validateForm() {
  var email = document.getElementById("email").value;
  var pattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
  var error = document.getElementById("email-error");
  if (!pattern.test(email)) {
    error.innerHTML = "Not a valid e-mail address";
    error.style.display = "block";
    return false;
  } else {
    error.innerHTML = "";
    error.style.display = "none";
  }
  return true;
}

In this code, we first get a reference to the error message element using the getElementById method.

Then, we use the innerHTML property to set the error message and the style.display property to show or hide the error message based on the validation result.


Conclusion

Form validation is an important aspect of web development that can be easily implemented using JavaScript.

By using conditional statements or regular expressions, you can validate form data on the client-side, providing a better user experience and reducing the load on the server.

In this tutorial, we have covered the basics of form validation using JavaScript, including how to check if the required fields are filled in, validate the data entered using regular expressions, and display error messages.

With these techniques, you can create robust and user-friendly forms for your web applications.