Form Validation in JavaScript

Kartikeya Mishra
3 min readSep 30, 2024

--

Form Validation in JavaScript

function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirmPassword').value;

// Name validation
if (name === '') {
alert('Name is required');
return false;
}

// Email validation
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
alert('Please enter a valid email');
return false;
}

// Password validation
if (password.length < 6) {
alert('Password must be at least 6 characters long');
return false;
}

// Confirm Password validation
if (password !== confirmPassword) {
alert('Passwords do not match');
return false;
}

alert('Form Submitted Successfully!');
return true;
}

// HTML Example
/*
<form onsubmit="return validateForm()">
<input type="text" id="name" placeholder="Name" />
<input type="email" id="email" placeholder="Email" />
<input type="password" id="password" placeholder="Password" />
<input type="password" id="confirmPassword" placeholder="Confirm Password" />
<button type="submit">Submit</button>
</form>
*/

Code Breakdown:

function validateForm() {
const name = document.getElementById('name').value;
const email = document.getElementById('email').value;
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirmPassword').value;
  1. Getting form inputs:
  • The function validateForm() is triggered when the form is submitted. It uses document.getElementById() to access the input fields by their id (e.g., 'name', 'email', etc.) and fetches their current values using .value.
  • These values are stored in variables: name, email, password, and confirmPassword.
    // Name validation
if (name === '') {
alert('Name is required');
return false;
}

2. Name field validation:

  • This checks if the name field is empty (i.e., the user has not entered a name).
  • If the field is empty, it triggers an alert() with the message "Name is required" and returns false to prevent form submission.
    // Email validation
const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailPattern.test(email)) {
alert('Please enter a valid email');
return false;
}

3. Email validation:

  • This uses a regular expression (emailPattern) to check if the email input follows a valid format, e.g., "someone@example.com".
  • If the email does not match this pattern, the function triggers an alert() asking for a valid email and prevents form submission by returning false.

Regex Explanation:

  • ^[^\s@]+ - The email should start with one or more characters that are not spaces or '@'.
  • @ - The "@" symbol must appear once.
  • [^\s@]+ - After the "@", there must be one or more characters that are not spaces or '@'.
  • \. - The domain should include a period (e.g., ".com").
  • [^\s@]+$ - After the period, there must be one or more characters, which is typically the domain suffix.
    // Password validation
if (password.length < 6) {
alert('Password must be at least 6 characters long');
return false;
}

4. Password length validation:

  • This checks if the password entered is at least 6 characters long.
  • If the password is shorter than 6 characters, an alert is shown (“Password must be at least 6 characters long”) and form submission is stopped by returning false.
    // Confirm Password validation
if (password !== confirmPassword) {
alert('Passwords do not match');
return false;
}

5. Password match validation:

  • This checks if the confirmPassword field matches the password field.
  • If the two passwords do not match, an alert is triggered (“Passwords do not match”) and submission is stopped by returning false.
    alert('Form Submitted Successfully!');
return true;
}

6. Final success message:

  • If all validations pass (name is filled, email is valid, password is long enough, and the passwords match), an alert is shown with the message “Form Submitted Successfully!” and the form is allowed to submit by returning true.

To see the validation in action, the HTML would look like this:

<form onsubmit="return validateForm()">
<input type="text" id="name" placeholder="Name" />
<input type="email" id="email" placeholder="Email" />
<input type="password" id="password" placeholder="Password" />
<input type="password" id="confirmPassword" placeholder="Confirm Password" />
<button type="submit">Submit</button>
</form>h

Summary:

  • The validateForm() function is designed to check the form inputs before submission.
  • It validates whether the name is not empty, the email is valid, the password is long enough, and that the two passwords match.
  • If any validation fails, an error message is shown, and the form will not be submitted.
  • If everything is correct, the form submission proceeds, and a success message is shown.

This is a simple yet effective form validation code that you can sell, offering basic but essential validation functionality for web forms.

Feel free to follow me on Twitter for more updates: https://x.com/DashForReall

And if you’d like to support my work, you can buy me a coffee here: https://buymeacoffee.com/coffeekartikeya

#JavaScript #WebDevelopment #Coding #OpenToWork #SoftwareDeveloper

--

--

Kartikeya Mishra

All about new technology in fun and easy way so that you can be confident in it and make your own piece of work using this knowledge !