JavaScript Program to Validate String for Uppercase, Lowercase, Special Characters, and Numbers
Last Updated :
16 Jul, 2024
In this article, we are going to learn how can we check if a string contains uppercase, lowercase, special characters, and numeric values. We have given string str of length N, the task is to check whether the given string contains uppercase alphabets, lowercase alphabets, special characters, and numeric values or not. If the string contains all of them, then returns “true”. Otherwise, return “false”.
Examples:
Input : str = "GeeksforGeeks@123"
Output : trueput: Yes
Explanation: The given string contains uppercase, lowercase,
special characters, and numeric values.
Input : str = “GeeksforGeeks”
Output : No
Explanation: The given string contains only uppercase
and lowercase characters.
Using Regular Expression
We can use regular expressions to solve this problem. Create a regular expression to check if the given string contains uppercase, lowercase, special character, and numeric values as mentioned below:
Syntax:
regex = “^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)” + “(?=.*[-+_!@#$%^&*., ?]).+$”
where,
- ^ represents the starting of the string.
- (?=.*[a-z]) represent at least one lowercase character.
- (?=.*[A-Z]) represents at least one uppercase character.
- (?=.*\\d) represents at least one numeric value.
- (?=.*[-+_!@#$%^&*., ?]) represents at least one special character.
- . represents any character except line break.
- + represents one or more times.
Match the given string with the Regular Expression using Pattern.matcher(). Print True if the string matches with the given regular expression. Otherwise, print False.
Example:This example shows the use of the above-explained approach.
JavaScript
// JavaScript Program to Check if a string contains
// uppercase, lowercase, special characters and
// numeric values
function isAllCharPresent(str) {
let pattern = new RegExp(
"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[-+_!@#$%^&*.,?]).+$"
);
if (pattern.test(str))
return true;
else
return false;
return;
}
// Driver Code
const str = "#GeeksForGeeks123@";
console.log(isAllCharPresent(str));
Using Array Methods
Convert the string to an array of characters. Utilize array methods like some() to check for uppercase, lowercase, special characters, and isNaN() to check for numeric values. Return the results in an object.
Example: In this example The function checkString analyzes a string for uppercase, lowercase, numeric, and special characters, returning an object indicating their presence. It's then tested with a sample string.
JavaScript
function checkString(str) {
const chars = Array.from(str);
const hasUppercase = chars.some(char => /[A-Z]/.test(char));
const hasLowercase = chars.some(char => /[a-z]/.test(char));
const hasNumeric = chars.some(char => !isNaN(char) && char !== ' ');
const hasSpecial = chars.some(char => /[!@#$%^&*(),.?":{}|<>]/.test(char));
return {
hasUppercase,
hasLowercase,
hasNumeric,
hasSpecial
};
}
const result = checkString("HelloWorld123!");
console.log(result);
Output{
hasUppercase: true,
hasLowercase: true,
hasNumeric: true,
hasSpecial: true
}
Using a Frequency Counter Object:
In this approach, we create an object to count the occurrences of each type of character (uppercase, lowercase, numeric, and special characters) in the string. Then, we check if each category has at least one occurrence.
JavaScript
function checkString(str) {
const charCount = {
uppercase: false,
lowercase: false,
numeric: false,
special: false
};
for (const char of str) {
if (/[A-Z]/.test(char)) {
charCount.uppercase = true;
} else if (/[a-z]/.test(char)) {
charCount.lowercase = true;
} else if (!isNaN(char) && char !== ' ') {
charCount.numeric = true;
} else if (/[!@#$%^&*(),.?":{}|<>]/.test(char)) {
charCount.special = true;
}
}
return charCount;
}
const result = checkString("HelloWorld123!");
console.log(result);
Output{ uppercase: true, lowercase: true, numeric: true, special: true }
Using Array.prototype.every
In this approach, we will create a function that uses the every method to check if all characters in the string meet certain criteria: uppercase, lowercase, numeric, and special characters.
Example: In this example, we will use the every method to check each character in the string.
JavaScript
function isAllCharPresent(str) {
const hasUppercase = [...str].some(char => /[A-Z]/.test(char));
const hasLowercase = [...str].some(char => /[a-z]/.test(char));
const hasNumeric = [...str].some(char => /\d/.test(char));
const hasSpecial = [...str].some(char => /[!@#$%^&*()_+\-=[\]{};':"\\|,.<>/?]/.test(char));
return hasUppercase && hasLowercase && hasNumeric && hasSpecial;
}
const str = "#GeeksForGeeks123@";
console.log(isAllCharPresent(str)); // Output: true
const str2 = "GeeksforGeeks";
console.log(isAllCharPresent(str2)); // Output: false
// Nikunj Sonigara
Using Set to Check Character Categories
In this approach, we will use a Set to store the different types of characters found in the string. This way, we can easily check if the string contains at least one of each required character type.
Example: This example demonstrates how to use Set to check if a string contains uppercase, lowercase, numeric, and special characters.
JavaScript
function isAllCharPresent(str) {
const charTypes = new Set();
const specialCharacters = new Set(['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '[', ']', '{', '}', ';', ':', '"', '\\', '|', ',', '.', '<', '>', '/', '?']);
for (const char of str) {
if (/[A-Z]/.test(char)) {
charTypes.add('uppercase');
} else if (/[a-z]/.test(char)) {
charTypes.add('lowercase');
} else if (/\d/.test(char)) {
charTypes.add('numeric');
} else if (specialCharacters.has(char)) {
charTypes.add('special');
}
}
return charTypes.has('uppercase') && charTypes.has('lowercase') && charTypes.has('numeric') && charTypes.has('special');
}
const str1 = "#GeeksForGeeks123@";
console.log(isAllCharPresent(str1));
const str2 = "GeeksforGeeks";
console.log(isAllCharPresent(str2));
Similar Reads
JavaScript Program to Check if a String Contains any Special Character This article will demonstrate the methods to write a JavaScript Program to check if a String contains any special characters. Any string that contains any character other than alphanumeric and space includes the special character. These special characters are '!', '@', '#', '$', '%', '^', '&', '
5 min read
JavaScript Program to Check Whether a String Starts and Ends With Certain Characters In this article, We are going to learn how can we check whether a string starts and ends with certain characters. Given a string str and a set of characters, we need to find out whether the string str starts and ends with the given set of characters or not. Examples: Input: str = "abccba", sc = "a",
3 min read
JavaScript - String Contains Only Alphabetic Characters or Not Here are several methods to check if a string contains only alphabetic characters in JavaScriptUsing Regular Expression (/^[A-Za-z]+$/) - Most USedThe most common approach is to use a regular expression to match only alphabetic characters (both uppercase and lowercase).JavaScriptlet s = "HelloWorld"
2 min read
JavaScript - Validate Password in JS To validate a password in JavaScript regex to ensure it meets common requirements like length, uppercase letters, lowercase letters, numbers, and special characters. we will validate a strong or weak password with a custom-defined range. JavaScriptlet regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@.
2 min read
JavaScript - Check if a String Contains Any Digit Characters Here are the various methods to check if a string contains any digital character1. Using Regular Expressions (RegExp)The most efficient and popular way to check if a string contains digits is by using a regular expression. The pattern \d matches any digit (0-9), and with the test() method, we can ea
4 min read
How to Check Case of Letter in JavaScript ? There are different ways to check the case of the letters in JavaScript which are explained below comprehensively, one can choose the method that best suits their specific use case and requirement.Table of ContentUsing the function "toUpperCase()" or "toLowerCase"Using regular expressionUsing ASCII
3 min read