Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

JavaScript Essentials - Forms and Validation

Handling forms and performing validation using JavaScript

Forms are a crucial part of web applications, allowing users to input data. This tutorial covers how to handle forms and perform validation using JavaScript to ensure the data entered by users is accurate and complete.

Key Points:

  • Forms are used to collect user input.
  • Validation ensures that the data entered by users is accurate and complete.
  • JavaScript can be used to handle form submissions and validate input data.

Creating a Form

Here is an example of a simple HTML form:






Handling Form Submission

You can handle form submission using the addEventListener() method to listen for the submit event. Here is an example:


document.getElementById('myForm').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent the default form submission

    var name = document.getElementById('name').value;
    var email = document.getElementById('email').value;

    console.log('Name: ' + name);
    console.log('Email: ' + email);
});
                

Validating Form Data

Validation ensures that the data entered by users is accurate and complete. Here is an example of validating the form data:


document.getElementById('myForm').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent the default form submission

    var name = document.getElementById('name').value;
    var email = document.getElementById('email').value;
    var errorElement = document.getElementById('error');
    var errorMessage = '';

    if (name === '') {
        errorMessage += 'Name is required. ';
    }

    if (email === '') {
        errorMessage += 'Email is required. ';
    } else if (!validateEmail(email)) {
        errorMessage += 'Email is not valid. ';
    }

    if (errorMessage !== '') {
        errorElement.textContent = errorMessage;
    } else {
        errorElement.textContent = '';
        console.log('Name: ' + name);
        console.log('Email: ' + email);
        // Here you can submit the form data to the server or perform other actions
    }
});

function validateEmail(email) {
    var re = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/;
    return re.test(String(email).toLowerCase());
}
                

Displaying Validation Errors

Validation errors can be displayed to the user to inform them of any issues with the data they have entered. Here is an example:






Summary

In this tutorial, you learned about handling forms and performing validation using JavaScript. You explored creating forms, handling form submission, validating form data, and displaying validation errors. Understanding these concepts is essential for creating user-friendly and reliable web applications.