JavaScript can change how a page looks at any moment, and can check what users type before it is sent to the server.

Manipulating CSS through JavaScript

Every element has a style property whose sub-properties match CSS properties in camelCase: element.style.color = "red"; element.style.backgroundColor = "#DEEAF6"; element.style.display = "none" (to hide). These set inline styles. A cleaner way is to change classes, keeping the styles in CSS: element.classList.add("error"), remove("error"), toggle("dark") and contains("active"). getComputedStyle(element) reads the final style that the browser applies. Uses include highlighting wrong fields, showing and hiding menus, dark mode switches and simple animations.

Definition: Form validation. The checking of the data entered in a form against rules, such as required fields, lengths and patterns, before it is accepted or sent to the server.

Why Validate Forms

Client-side validation checks data in the browser before it is sent. It gives the user instant feedback, reduces load on the server and avoids wasted round trips. It does not replace server-side validation, since a user can switch off JavaScript or send data directly, so the server must check again. HTML5 provides built-in validation attributes, and JavaScript adds custom checks and messages.

Types of Validators

A required validator checks that a field is not empty: HTML required, or in JavaScript value.trim() === "". A length validator checks the number of characters: minlength and maxlength, or value.length < 8. A range validator checks numbers: min and max. A pattern validator checks the format with a regular expression: the pattern attribute, or regex.test(value). A compare validator checks that two fields match, such as a password and its confirmation.

Regular Expressions

A regular expression (regex) describes a text pattern, written between slashes: /^[0-9]{10}$/. ^ and $ mark the start and end, [0-9] or \d is a digit, [A-Za-z] a letter, \w a word character, {n} exactly n times, {m,n} between m and n times, + one or more, zero or more, ? optional, and . any character. Examples: a 10-digit mobile number /^[6-9]\d{9}$/; an email /^[\w.]+@[\w]+\.[a-z]{2,}$/; a strong password /^(?=.[A-Z])(?=.*\d).{8,}$/ (at least 8 characters, one capital and one digit).

The Validation Flow

A submit handler checks each rule, shows messages next to the wrong fields, and calls event.preventDefault() to stop submission if any check fails.

Table 4.1: Validators

Validator Checks Example rule
Required Field not empty name.trim() !== ""
Length Number of characters password.length >= 8
Range Numeric limits 18 <= age <= 60
Pattern Format by regex /^[6-9]\d{9}$/ for mobile
Compare Two fields match pwd === confirm

Example 4.1: Validating a login form

Problem: Validate a login form: the username is required, the password must have at least 8 characters with a capital letter and a digit, and the mobile number must be 10 digits starting with 6 to 9. Highlight wrong fields in red.

Solution:

  1. In the submit handler, read the three values.
  2. Test required, length and pattern rules with regular expressions.
  3. For each failure, add an error class and collect a message.
  4. If there are errors, call preventDefault() and show the messages.

Result: The form is sent only when every rule passes; wrong fields turn red.

function validate(user, pwd, mobile) {
  const errors = [];
  if (user.trim() === "") errors.push("Username is required");
  if (pwd.length < 8) errors.push("Password needs 8+ characters");
  else if (!/^(?=.*[A-Z])(?=.*\d)/.test(pwd))
    errors.push("Password needs a capital letter and a digit");
  if (!/^[6-9]\d{9}$/.test(mobile))
      errors.push("Mobile must be 10 digits");
  return errors.length ? errors : ["All fields valid"];
}
console.log(validate("", "abc", "12345"));
console.log(validate("asha", "Secret123", "9876543210"));

Output

[
  'Username is required',
  'Password needs 8+ characters',
  'Mobile must be 10 digits'
]
[ 'All fields valid' ]

Common mistakes

  • Relying only on client-side validation without checking on the server.
  • Writing a regex without ^ and $, so that it matches part of the input only.
  • Setting many inline styles instead of toggling a CSS class.

Key takeaways

  • element.style and classList change CSS from JavaScript.
  • Validators check required, length, range, pattern and compare rules.
  • Regular expressions describe formats such as mobile numbers and emails.
  • Call preventDefault() to stop a form that fails validation.

Practice questions

  1. Why must the server validate data even when the browser does?
  2. Write a regex for exactly six digits.
  3. How do you add a CSS class to an element in JavaScript?

Answers to the practice questions

  1. Because client-side checks can be bypassed by disabling JavaScript or sending data directly.
  2. /^\d{6}$/.
  3. element.classList.add("name").

Sources

  • Official BCA syllabus Web Technologies, course code 25BCA402SEC02, Unit IV