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 Two Strings are Same or Not
In this article, we are going to implement a JavaScript program to check whether two strings are the same or not. If they are the same then we will return true else we will return false. Examples: Input: str1 = Geeks, str2 = GeeksOutput: True. Strings are the SameInput: str1 = Geeks, str2 = GeekOutp
4 min read
JavaScript Program to Test if Kth Character is Digit in String
Testing if the Kth character in a string is a digit in JavaScript involves checking the character at the specified index and determining if it is a numeric digit. Examples:Input : test_str = âgeeks9geeksâ, K = 5 Output : True Explanation : 5th idx element is 9, a digit, hence True.Input : test_str =
5 min read
JavaScript Program to Match Single Character with Multiple Possibilities
In this article, we will write programs to check all possible matching in JavaScript. We will check the occurrence of characters individually in the given string or sequence. In this article, we will check the occurrence of vowels in the given string. Table of Content Using JavaScript RegExp test()
3 min read
JavaScript Program to Check if a Character is Vowel or Not
In this article, we will check if the input character is a vowel or not using JavaScript. Vowel characters are âaâ, âeâ, âiâ, âoâ, and âuâ. All other characters are not vowels. Examples: Input : 'u'Output : TrueExplanation: 'u' is among the vowel characters family (a,e,i,o,u).Input : 'b'Output : Fal
4 min read
JavaScript - String Contains Only Alphabetic Characters or Not
Here are several methods to check if a string contains only alphabetic characters in JavaScript Using 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). [GFGTABS] JavaScript let s =
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. [GFGTABS] JavaScript let regex = /^(?=.*[a-z])(?=.*[A-Z])(?=.*
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 character 1. 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 e
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 Content Using the function "toUpperCase()" or "toLowerCase"Using regular expressionUsing ASCI
3 min read
JavaScript - Compare Two Strings
These are the followings ways to compare two strings: 1. Using strict equality (===) operatorWe have defined a function that compare two strings using the strict equality operator (===), which checks if both the value and the type of the operands are equal. [GFGTABS] JavaScript let str1 = "hell
2 min read
PHP Program to Check if a String Contains Uppercase, Lowercase, Special Characters and Numeric Values
Given a String, the task is to check whether the given string contains uppercase, lowercase, special characters, and numeric values in PHP. When working with strings in PHP, it's often necessary to determine the presence of certain character types within the string, such as uppercase letters, lowerc
3 min read