View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
  1. Home
image

JavaScript Tutorial Concepts - From Beginner to Pro

Learn JavaScript from scratch! Our tutorial covers basics to advanced concepts. Start learning today!

  • 24
  • 9 Hours
right-top-arrow
12

JavaScript Form Validation

Updated on 07/08/2024344 Views

My journey as a developer with JavaScript form validation began with simple checks for empty fields. It quickly evolved into crafting clear error messages to guide users. As my forms grew in complexity, I started using regular expressions to ensure data followed specific patterns.

These experiences taught me how a well-validated form boosts user experience. Seeing instant feedback and avoiding frustrating form rejections significantly impacts the way users interact with my websites.

Let us learn all about JavaScript form validation and how to effectively use it for our projects. I will also show you some examples that you can try out yourself in this JavaScript form validation tutorial for beginners and intermediate developers.

What is JavaScript Form Validation?

Form validation is the process of verifying that the data entered by a user into a web form meets specific requirements before it's submitted. This involves checking for:

  • Required fields: Ensuring that all mandatory fields have been filled in.
  • Data format: Verifying that data matches the expected type and structure (e.g., emails, dates, numbers).
  • Range and constraints: Checking if values fall within acceptable ranges (e.g., age limits, password strength).
  • Logical consistency: Validating relationships between different fields (e.g., password and confirmation password matching).

Why JavaScript Form Validation Matters

Here is why JavaScript form validation matters:

  • User Experience (UX)
    • Immediate feedback: Real-time validation guides users in filling out the form correctly, preventing frustration from errors discovered only after submission.
    • Clear error messages: Specific error messages help users quickly understand and fix input problems.
  • Data integrity
    • Data quality: Validation ensures that data collected is accurate, consistent, and usable for its intended purpose.
    • Malicious input prevention: It helps protect against invalid data or attempts to inject harmful code.

Client-side vs. Server-side JavaScript Form Validation

Here is the difference between client-side and server-side JavaScript form validation:

  • Client-side:
    • First line of defense: Provides immediate validation in the browser, catching errors early in the process.
    • User-friendly: Instant feedback improves the form-filling experience.
    • Reduced Server Load: Prevents unnecessary round trips to the server for basic validation checks.
  • Server-side:
    • Essential for security: Never trust data from the client. Server-side validation is non-bypassable and protects our application from malicious attacks.
    • Complex logic: Handles validation that requires database lookups or calculations that client-side JavaScript may not be able to perform

Benefits of JavaScript Validation

Here are the benefits of using JavaScript form validation:

  • Immediacy: Errors are highlighted as the user types or moves to the next field, leading to faster corrections.
  • User-friendliness: Well-designed error messages improve the experience and reduce abandonment of forms.
  • Reduced server load: Filtering out invalid submissions early unburdens our server and improves responsiveness.

Basic Validation with HTML5

HTML5 validation is excellent for simple scenarios. For more sophisticated forms, custom JavaScript validation is our best friend, letting us tailor error messages, implement advanced checks, and ultimately provide a superior user experience.

HTML5 introduced several attributes that streamline basic form validation directly within our HTML structure. Let’s explore some methods.

  • required: Marks a field as mandatory. The form won't submit if it's empty.

Example:

<input type="text" required> 

  • minlength, maxlength: Set minimum and maximum allowed characters for text input.

Example:

<input type="password" minlength="8" maxlength="20">

  • pattern: Enforce a format using regular expressions.

Example:

<input type="text" pattern="[0-9]{5}"> 

  • input type: Specialize inputs for emails, numbers, dates, etc., with built-in browser checks.

Example:

<input type="email">

<input type="number">

<input type="date">

Limitations of HTML5 Validation

While useful, HTML5 validation has its limits:

  • Customizability: Error messages are browser-controlled and less customizable than JavaScript solutions.
  • Complex logic: Can't handle things like comparing fields, password strength checks, or data pulled from a database.
  • Accessibility: We might need extra work for error messages to work well with screen readers.
  • Bypassable: Since it's client-side, it's not secure on its own.

Core JavaScript Form Validation Techniques

Let us explore some core techniques with the help of JavaScript form validation program examples.

Form & Element References

Before validating, we need to grab the right elements from the DOM:

  • document.forms: Allows us to access forms on a page. You might reference a form by its name (document.forms['myForm']) or index.
  • getElementById: The classic way to get a single element by its unique id attribute.
  • querySelector: A flexible selector. Use it to target elements by ID, tag name, class, or with more complex CSS selectors.

Checking Input

Here's where the core logic of validation happens:

  • Empty fields: Check if input.value is an empty string after trimming whitespace.
  • Basic format checks: For an email-like structure, you could have a simple check for the presence of an '@' symbol and a domain-like component (.com, .net, etc.). I would like to mention that this is a very rudimentary email check, true validation is better done with regular expressions.

Error Display

Providing clear feedback to the user is essential:

  • Creating error elements: Use document.createElement('span') or similar to dynamically create an element to hold your error message.
  • Styling: Often, a class like "error-message" is added, and CSS gives these messages a distinct look (usually red text).
  • Placement:
    • Inline: Insert the error message directly next to the problematic field.
    • Summary: Display a list of all errors at the top of the form.

JavaScript Form Validation Code Example

Here is a JavaScript form validation example with source code:

function validate() {

  const emailInput = document.getElementById('email');

  if (emailInput.value.trim() === '') {

    // Create an error message element if it doesn't exist

    // Add styling, insert it next to the email input...

    return false; // Prevent form submission if there are errors 

  }

  // ... more validation logic

  return true; // Allow form submission if all good

}

// Attach validate() to your form's 'submit' event

A full validation solution would handle error removal when the user corrects input.

This is just the beginning as real-world forms usually have many more input fields and various checks. 

Let us now check a more defined HTML CSS JavaScript form validation example that you can try out yourself.

After compilation:

Error message when we do not use ‘@’:

Code for index.html:

<form id="signupForm" onsubmit="return validateForm()"> 

  <div>

    <label for="email">Email:</label>

    <input type="email" id="email" required>

  </div>

  <div>

    <label for="password">Password:</label>

    <input type="password" id="password" minlength="8">

  </div>

  <button type="submit">Sign Up</button>

</form>

Code for styles.css:

/* Style for the form container - optional */

#signupForm {

  width: 400px;

  margin: 20px auto;

  padding: 20px;

  border: 1px solid #ddd;

}

/* Style for error messages */

.error-message {

  color: red;

  font-size: 0.9em; 

  margin-top: 5px; 

}

Code for script.js:

function validateForm() {

  const emailInput = document.getElementById('email');

  const passwordInput = document.getElementById('password');

  let isValid = true; // Start with optimism!

  // Clear any previous error messages (not shown for brevity)

  // Email Validation (slightly more advanced)

  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // A basic email pattern

  if (!emailRegex.test(emailInput.value)) {

    displayError(emailInput, "Please enter a valid email address.");

    isValid = false;

  }

  // Password: Length & Strength (hypothetical)

  if (passwordInput.value.length < 8) {

    displayError(passwordInput, "Password must be at least 8 characters.");

    isValid = false; 

  } else if (!hasStrongPassword(passwordInput.value)) { 

    displayError(passwordInput, "Password should contain a mix of characters.");

    isValid = false; 

  }

  return isValid; 

}

// Helper function (you'd implement these)

function displayError(inputElement, message) { 

  // ... Logic to create error message, style, and insert ...

}

function hasStrongPassword(password) {

  // ... Logic to check for uppercase, special characters, etc ...

}

In the above JavaScript form validation source code, we are using required and minlength on input fields with with help of HTML5. Also, a slightly better email check is introduced with Regex. In this code, the hasStrongPassword function would contain your specific rules.

We encapsulate error display and password strength logic for better organization. The form calls validateForm. Only if it returns true will the form actually submit.

Now that I have covered this simple, JavaScript form validation for email, let us check out some more advanced concepts of JavaScript form validation.

Advanced JavaScript Form Validation Concepts

Regular Expressions (Regex)

Regex is a language for defining text patterns. It's immensely powerful for form validation.

Regex uses special characters like:

  • ^ & $: Match string start and end.
  • .: Wildcard for any single character.
  • [a-z]: Character classes, matching a range.
  • \d: Digits (0-9).
  • {n}: Quantifier: Repeat the previous element 'n' times.

Common patterns:

  • Email (Simplified): /^[^@]+@[^@]+\.[^@]+$/ ('something@something.something')
  • US Phone (10 digits): /^\d{10}$/
  • Stronger Password: (?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[!@#$%^&*]).{8,}

We can test Regex with:

  • JavaScript: The .test() method on strings

Password Strength

  • Length Check: if (passwordInput.value.length < 8) ...
  • Character Requirements (Lookaheads):
    • (?=.*\d): At least one digit.
    • (?=.*[a-z]): At least one lowercase letter.
    • (?=.*[A-Z]): At least one uppercase letter.
    • (?=.*[!@#$%^&*]): At least one special character.

Comparing Fields

  • Password match:

if (passwordInput.value !== confirmPasswordInput.value) {

    displayError(confirmPasswordInput, "Passwords must match.");

}

  • Cross-field logic: You might compare dates, check if a "total" field is correct based on calculations from other inputs, etc.

Validation Functions

function isValidEmail(email) {

  const emailRegex =  /^[^@]+@[^@]+\.[^@]+$/; 

  return emailRegex.test(email); 

}

function isStrongPassword(password) {

  // ... Logic from earlier ...

}

// Inside your validation:

if (!isValidEmail(emailInput.value)) { 

    // ... display error ...

}

JavaScript Form Validation Codepen Project

Here is a JavaScript form validation project you can build on Codepen:

Code for HTML:

<form id="contactForm" onsubmit="return validateContact()">

  <div>

    <label for="phoneNumber">Phone Number:</label>

    <input type="tel" id="phoneNumber">

  </div>

  <div>

    <label for="message">Your Message:</label>

    <textarea id="message" rows="5" required></textarea>

  </div>

  <button type="submit">Send Message</button>

</form>

Code for JS:

function validateContact() {

  const phoneNumberInput = document.getElementById('phoneNumber');

  const messageInput = document.getElementById('message');

  let isValid = true;

  // Clear any previous errors ...

  // Phone Number: Basic Format Check

  const phoneRegex = /^\d{10}$/; // A simple 10-digit pattern

  if (!phoneRegex.test(phoneNumberInput.value)) {

    displayError(phoneNumberInput, "Please enter a valid 10-digit phone number.");

    isValid = false;

  }

  // Message:  Minimum Length 

  if (messageInput.value.trim().length < 20) {

    displayError(messageInput, "Message should be at least 20 characters.");

    isValid = false;

  }

  return isValid;

}

// ... displayError function (as before) ... 

If you wish to master essential JS concepts like the JavaScript DOM functions, you can enroll in any of the full stack development courses by upGrad.

Wrapping Up

JavaScript form validation puts control in the developer's hands. It empowers us to create smoother user experiences and protect the integrity of our data. While always requiring secure server-side checks, client-side validation demonstrates a commitment to well-crafted, user-centric web applications.

If you wish to master technologies such as JavaScript, you can enroll in upGrad’s software engineering courses.

Frequently Asked Questions

1. Can JavaScript be used to validate forms?
Yes, JavaScript is a primary tool used for form validation.

2. Why form validation is required in JavaScript?
JavaScript form validation is required to ensure data is correct and in the right format before it's submitted to the server, improving user experience and data quality.

3. What are the benefits of using JavaScript for form validation?

  • Immediate feedback to the user, preventing unnecessary server requests.
  • Enhanced user experience with clear error messages.
  • Improved data integrity by catching errors early.

4. Why JavaScript form data validation is not secure?
JavaScript form validation is not secure on its own because it happens on the client-side (in the browser) and can be bypassed. Always perform server-side validation for security.

5. In which part does form validation occur?
Form validation can occur both on the client-side (in the browser using JavaScript) and on the server-side.

6. Can we validate form without JavaScript?
Yes, HTML5 has built-in form validation attributes like required, pattern, minlength, and maxlength.

7. How many types of form validation are there in JavaScript?
There's no fixed number, but JavaScript form validation can be as simple or complex as needed, tailored to your specific requirements.

8. What are the different types of form validation?
Common validation types include: checking for empty fields, validating email formats, password strength, data types, matching values, and more.

9. What is basic form validation in JavaScript?
Basic form validation in JavaScript often involves checking if required fields are filled out, simple format checks (like basic email structure), and ensuring data types are correct.

Get Free Career Counselling
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. .