Source: pages-sections/SignUp-Sections/validateCredentials.js

// authUtils.js
import validatePassword from "./validatePassword";

/**
 * The `validateCredentials` function in JavaScript validates the user's credentials
 * when signing up for an account.
 * @param username - The username entered by the user.
 * @param password - The password entered by the user.
 * @param reconfirmPassword - The re-entered password for confirmation.
 * @param email - The email entered by the user.
 * @returns The function returns an error message if the credentials are invalid.
 * If the credentials are valid, the function returns null.
 * The function checks the following conditions:
 * - Username must be at least 8 characters long and must not contain special characters.
 * - Password must be at least 8 characters long and must contain at least one uppercase letter,
 * one lowercase letter, one number, and one special character.
 * - The re-entered password must match the original password.
 * - Email must be in a valid email format.
 */

export function validateCredentials(
  username,
  password,
  reconfirmPassword,
  email
) {
  let specialChars = /[!@#$%^&*(),.?":{}|<>]/;
  let hasSpecial, hasNumber, hasUpperCase, hasLowerCase;
  hasSpecial = hasNumber = hasUpperCase = hasLowerCase = false;

  hasSpecial = specialChars.test(username);
  if (username.length < 8 || hasSpecial) {
    return "Username must be at least 8 characters long and must not contain special characters";
  }

  let results = validatePassword(password, reconfirmPassword);
  if (results) {
    return results;
  }

  let emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!emailRegex.test(email)) {
    return "Invalid email format";
  }

  return results; // Validation passed
}