Back to JavaScript
2025-12-227 min read

Sign Up for Free (JavaScript)

Learn Sign Up for Free (JavaScript) step by step with clear examples and exercises.

Title: Sign Up for Free (JavaScript)

Why This Matters

today, web applications have become an integral part of our lives, and learning JavaScript is essential to create interactive and dynamic websites. One crucial aspect of building a web application is user registration, where users can sign up for free to access the services provided. In this lesson, we will delve into creating a simple yet effective free sign-up form using JavaScript.

Prerequisites

To follow along with this tutorial, you should have a basic understanding of HTML and CSS. Additionally, it's essential to be familiar with JavaScript variables, functions, events, DOM manipulation, and regular expressions. If you are new to these topics, consider reviewing our previous lessons on HTML, CSS, and JavaScript basics before proceeding.

### Importance of Prerequisites

Understanding the prerequisites is crucial for a successful learning experience. Having a strong foundation in HTML, CSS, and JavaScript will help you grasp the concepts presented in this lesson more easily.

Core Concept

To create a sign-up form, we will use HTML for the structure, CSS for styling, and JavaScript for functionality. First, let's set up our HTML document:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sign Up Form</title>
<!-- Add your CSS file here -->
</head>
<body>
<h1>Sign Up for Free</h1>
<form id="signupForm">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username"><br>
<span class="error-message username-error"></span><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<span class="error-message email-error"></span><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password"><br>
<span class="error-message password-error"></span><br>
<button type="submit">Sign Up</button>
</form>
<!-- Add your JavaScript file here -->
</body>
</html>

Now, let's add some JavaScript to handle the form submission and validate user input:

document.getElementById("signupForm").addEventListener("submit", function(event) {
event.preventDefault(); // Prevent the page from refreshing on submit

const username = document.getElementById("username").value;
const email = document.getElementById("email").value;
const password = document.getElementById("password").value;

if (!validateUsername(username)) {
displayErrorMessage("username-error", "Invalid username.");
return;
}

if (!validateEmail(email)) {
displayErrorMessage("email-error", "Invalid email address.");
return;
}

if (!validatePassword(password)) {
displayErrorMessage("password-error", "Weak password. Please use a combination of letters, numbers, and symbols.");
return;
}

// If all validations pass, save user data or show success message
});

function validateUsername(username) {
const regex = /^[a-zA-Z0-9_]{3,20}$/; // Allow only alphanumeric characters and underscores (no spaces) with a minimum length of 3 characters and maximum length of 20 characters.
return regex.test(username);
}

function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}

function validatePassword(password) {
const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/; // Require at least one uppercase letter, one lowercase letter, one number, and one special character, with a minimum length of 8 characters.
return re.test(String(password));
}

function displayErrorMessage(errorId, message) {
const errorElement = document.getElementById(errorId);
errorElement.textContent = message;
}

In the above code, we've added an event listener to our form that prevents page reloading on submission. We then retrieve the user input values and perform validations for each field using custom functions: validateUsername(), validateEmail(), and validatePassword(). Additionally, we have created a function called displayErrorMessage() to show error messages when there is invalid data in any of the fields.

Worked Example

Let's create a simple username validation function that checks for minimum length (3 characters) and maximum length (20 characters):

function validateUsername(username) {
if (username.length < 3 || username.length > 20) {
return false;
}
return true;
}

Next, we can create an email validation function using regular expressions to check for a valid email format:

function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}

Lastly, we can create a password validation function that checks for the presence of at least one uppercase letter, one lowercase letter, one number, and one special character:

function validatePassword(password) {
const re = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$/;
return re.test(String(password));
}

Common Mistakes

### Incorrect Username Validation

Ensure your username validation function checks for the correct length and allows only alphanumeric characters and underscores (no spaces).

### Weak Password Validation

Make sure your password validation function requires a strong password containing at least one uppercase letter, one lowercase letter, one number, and one special character.

### Incorrect Email Validation

Ensure your email validation function checks for the correct format, including the '@' symbol and domain extension.

### Improper Error Handling

When handling errors, make sure to display error messages for each invalid input field when the form is submitted with incorrect data.

### Incomplete Form Submission Prevention

Ensure that the event listener prevents the page from reloading upon form submission and only calls the validation functions after the user has filled out all required fields.

Practice Questions

  1. Modify the username validation function to allow only alphanumeric characters and underscores (no spaces).
  2. Implement a password strength indicator that shows the user how strong their password is based on the length and complexity requirements.
  3. Add error messages for each invalid input field when the form is submitted with incorrect data.
  4. Improve the email validation function to handle international email addresses, including those using different domain extensions (e.g., .co.uk, .de, etc.).
  5. Implement a function that checks if the provided username is already taken in the database. If it is, display an error message and prevent form submission.
  6. Add a feature to store user data securely after successful form submission.
  7. Implement a function that sends an email confirmation to the user's provided email address upon successful form submission.
  8. Create a function that generates a unique password for the user if they do not provide one during registration.
  9. Implement a function that allows users to log in using their registered username and password.
  10. Add a feature that allows users to reset their password if they forget it.

FAQ

### Why do we need to validate user input?

Validating user input helps ensure the integrity of our application by preventing malicious attacks, such as SQL injection, and providing a better user experience by ensuring users enter valid data.

### How can I improve my password validation function?

To improve your password validation function, consider adding additional requirements like requiring a minimum length of 12 characters or checking for common password patterns (e.g., sequential numbers, dictionary words).

### What happens when the user submits the form with invalid data?

When the user submits the form with invalid data, our JavaScript code will display error messages for each invalid input field and prevent the page from reloading. This allows users to easily correct their mistakes and resubmit the form.

### How can I handle international email addresses in my validation function?

To handle international email addresses, you can modify your regular expression to account for different domain extensions (e.g., .co.uk, .de, etc.). You may also want to research specific email formats for each country to ensure comprehensive coverage.

### How can I store user data securely after successful form submission?

To store user data securely, consider using a hashing algorithm like SHA-256 or bcrypt to protect passwords and encrypt sensitive information before storing it in your database. Additionally, make sure to follow best practices for database security, such as limiting access to the database and implementing regular backups.

### How can I send an email confirmation to the user's provided email address upon successful form submission?

To send an email confirmation, you can use a service like SendGrid or Mailgun that allows you to send emails programmatically. You will need to sign up for an account, create an API key, and then integrate their SDK into your project to send the confirmation email.

### How can I generate a unique password for the user if they do not provide one during registration?

To generate a unique password, you can use a combination of random letters, numbers, and symbols. You may also want to consider implementing a password policy that ensures the generated password meets complexity requirements (e.g., minimum length, presence of uppercase and lowercase letters, numbers, and special characters).

### How can I allow users to log in using their registered username and password?

To implement user login functionality, you will need to create a login form where users can enter their username and password. Upon successful submission, you can check the provided credentials against your database and, if they match, grant access to the user's account. You may also want to consider implementing additional security measures like rate limiting and CAPTCHA to prevent brute force attacks.

### How can I reset a user's password if they forget it?

To implement a password reset feature, you will need to create a password reset form where users can enter their email address. Upon successful submission, you can send an email with a unique token to the user's email address. The user can then visit a specific URL containing the token and set a new password for their account. Make sure to securely store and validate the token to prevent unauthorized access.

Sign Up for Free (JavaScript) | JavaScript | XQA Learn