Can we do regex pattern checking for password validation in reactJS?
Since I am new to reactJS, I need regex pattern for validating the password.
Following are the conditions for validating password.
a) Password should contains one Capital letter
b) It should start with special character # or #
c) It should not contain any vowel a,e,i,o,u letters
d) It should be alphanumeric.
e) Length of password should be between range 8 to 14
The simpliest way is to check all rules separately.
There's a function i wrote for you:
function password_validate(password) {
var re = {
'capital' : /[A-Z]/,
'digit' : /[0-9]/,
'except' : /[aeiou]/,
'full' : /^[##][A-Za-z0-9]{7,13}$/
};
return re.capital .test(password) &&
re.digit .test(password) &&
!re.except .test(password) &&
re.full .test(password);
}
Or the same function in one line:
function password_validate(p) {
return /[A-Z]/.test(p) && /[0-9]/.test(p) && !/[aeiou]/.test(p) && /^[##][A-Za-z0-9]{7,13}$/.test(p);
}
This regex will work :
^[##](?=.{7,13}$)(?=\w{7,13})(?=[^aeiou_]{7,13})(?=.*[A-Z])(?=.*\d)
Explanation
^[##] Starts with # or #
Now we can add some conditions this way :
(?=condition)(?=condition)(?=condition)
This means "match condition but after that continue matching at the original match-point."
You can add as many conditions as you want, and this will be an "and."
(?=.{7,13}$) Length of password should be between range 8 to 14
(?=\w{7,13}) It should be alphanumeric.
(?=[^aeiou_]{7,13}) It should not contain any vowel a,e,i,o,u letters or underscore which is matched by \w
(?=.*[A-Z]) Password should contains a Capital letter
(?=.*\d) It should be alphanumeric so it should contain a digit
Demo
If you want to check all rules in one pass - try this formula:
^([##](?=[^aeiou]{7,13}$)(?=[[:alnum:]]{7,13}$)(?=.*[A-Z]{1,}.*$).+)$
Demo
Standard one - /^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##\$%\^&\*])(?=.{8,})/.test(paswrd)
Related
I'm very new to learning RegEx, and need a little help updating what I have. I will use it to evaluate student spreadsheet functions. I know it isn't perfect, but I'm trying to use this as a stepping stone to a better understanding of RegEx. I currently have [DE45\\+\\s]*$ but it does not validate for criteria #4 below. Any help is greatly appreciated.
I need to validate an input so that it matches these four criteria:
Letters D and E: (UPPERCASE, in any order, in any length string)
Numbers 4 and 5: (in any order, in any length string) Special
Characters: comma (,) and plus (+) (in any order, in any length string)
All six characters DE45+, must be present in the string at least once.
Results
pass: =if(D5>0,E4+D5,0)
pass: =if(D5>0,D5+E4,0)
fail: Dad Eats # 05:40
pass: Dad, Eats+Drinks # 05:40
fail: =if(E4+D5)
pass: DE45+,
The attempt you made -- with a character class -- will not work since [DE45] matches any single character in the class -- not all of them.
This type of problem is solved with a series of anchored lookaheads where all of these need to be true for a match at the anchor:
^(?=.*D)(?=.*E)(?=.*\+)(?=.*4)(?=.*5)(?=.*,)
Demo
Lookaround tutorial
Also, depending on the language, you can chain logic with regex matches. In Perl for example you would do:
/D/ && /E/ && /\+/ && /4/ && /5/ && /,/
In Python:
all(re.search(p, a_str) for p in [re.escape(c) for c in 'DE45+,'])
Of course easier still is to use a language's set functions to test that all required characters are present.
Here in Python:
set(a_str) >= set('DE45+,')
This returns True only if all the characters in 'DE45+,' are in a_str.
A Regular Expression character class (in the square brackets) is an OR search. It will match if any one of the characters in it is present, which does not allow you to verify #4.
For that you could build on top of a regex, as follows:
Find all instances of any of the characters you're looking for individually with a simple character class search. (findall using [DE45+,]+)
Merge all the found characters into one string (join)
Do a set comparison with {DE45+,}. This will only be True if all the characters are present, in any amount and in any order (set)
set(''.join(re.findall(r'[DE45+,]+','if(D5>0,4+D5,0)E'))) == set('DE45+,')
You can generalize this for any set of characters:
import re
lookfor = 'DE45+,'
lookfor_re = re.compile(f'[{re.escape(lookfor)}]+')
strings = ['=if(D5>0,E4+D5,0)', '=if(D5>0,D5+E4,0)', 'Dad Eats # 05:40', 'Dad, Eats+Drinks # 05:40', '=if(E4+D5)', 'DE45+,']
for s in strings:
found = set(''.join(lookfor_re.findall(s))) == set(lookfor)
print(f'{s} : {found}')
Just set lookfor as a string containing each of the characters you're looking for and strings as a list of the strings to search for. You don't need to worry about escaping any special characters with \. re.escape does this for you here.
=if(D5>0,E4+D5,0) : True
=if(D5>0,D5+E4,0) : True
Dad Eats # 05:40 : False
Dad, Eats+Drinks # 05:40 : True
=if(E4+D5) : False
DE45+, : True
I want to write a regular expression that matches all 9-letter words in a word list that contain only one vowel; for example, "strengths".
The best I've achieved is:
^(([^aeiou]{8}[aeiou])|
([^aeiou]{7}[aeiou][^aeiou]{1})|
([^aeiou]{6}[aeiou][^aeiou]{2})|
([^aeiou]{5}[aeiou][^aeiou]{3})|
([^aeiou]{4}[aeiou][^aeiou]{4})|
([^aeiou]{3}[aeiou][^aeiou]{5})|
([^aeiou]{2}[aeiou][^aeiou]{6})|
([^aeiou]{1}[aeiou][^aeiou]{7})|
([aeiou][^aeiou]{8}))$
(linebreaks added for readability). This works, but is there a way to do it with a more general pattern such as:
^[^aeiou]*[aeiou][^aeiou]*$
by adding a "fail if length is not 9" condition in some way?
Use a lookahead to limit the length and accept only letters:
^(?=[a-z]{9}$)[^aeiou]*[aeiou][^aeiou]*$
You may use
^(?=.{9}$)[b-df-hj-np-tv-z]*[aeiou][b-df-hj-np-tv-z]*$
See the regex demo. Add a case insensitive flag to also match uppercase letters.
*Details
^ - start of a string
(?=.{9}$) - a *positive lookahead that makes sure the string contains any 9 chars (else, fail the match)
[b-df-hj-np-tv-z]* - 0+ consonants
[aeiou] - a vowel
[b-df-hj-np-tv-z]* - 0+ consonants
$ - end of string.
adding a "fail if length is not 9" condition in some way?"
The best way is to not check the string length using a regex.
Use the functionality provided by the language you use to check the string length then use a regex to check that it contains only the accepted characters and it includes one wovel.
A simple example in JavaScript (rewriting it in any other language is an easy task):
var input = 'some input string';
if (input.length == 9 && input.match(/[aeiou]/)) {
console.log('Valid input (length is 9 and contains at least one wovel)');
} else {
console.log('Invalid input');
}
I would like to allow these characters [a-z]+\.+[0-9]*\_* (Must contain one or more lowercase alphabetical characters(a-z) and Must contain one or more periods(.) also can contain zero or more digits(0-9), zero or more underscores(_)) , but no others.
I have tried multiple ways without success:
import re
iStrings = str(input('Enter string? '))
iMatch = re.findall(r'[a-z]+\.+[0-9]*\_*', iStrings)
iiMatch = re.findall(r'[~`!#$%^&*()-+={}\[]|\;:\'"<,>.?/]', iStrings)
iiiMatch = iMatch != iiMatch
if iiiMatch:
print(':)')
else:
print(':(')
Another example:
import re
iStrings = str(input('Enter string? '))
iMatch = re.findall(r'[a-z]+\.+[0-9]*\_*', iStrings) not "[~`!#$%^&*()-+={}\[]|\;:\'"<,>.?/]" in iStrings
if iMatch:
print(':)')
else:
print(':(')
Any help would be much appreciated.
Edit: added clarification.
Edit: For additional information: https://forums.uberent.com/threads/beta-mod-changes.51520/page-8#post-939265
allow these characters [a-z]+\.+[0-9]*\_*
First off, [a-z]+ is not "a" character. Neither is [0-9]* nor \_*
I am assuming that you mean you want to allow letters, digits, underscores, dots, plusses and asterisks.
Try this:
^[\w*.+]+$
The \w already matches [a-z], [0-9] and _
The anchors ^ and $ ensure that nothing else is allowed.
From your question I wasn't clear if you wanted to allow a + character to match. If not, remove it from the character class: ^[\w*.]+$. Likewise, remove the * if it isn't needed.
In code:
if re.search(r"^[\w*.+]+$", subject):
# Successful match
else:
# Match attempt failed
EDIT following your comment:
For a string that must contain one or more letter, AND one or more dot, AND zero or more _, AND zero or more digits, we need lookaheads to enforce the one or more conditions. You can use this:
^(?=.*[a-z])(?=.*\.)[\w_.]+$
This question already has answers here:
Regexp Java for password validation
(17 answers)
Closed 8 years ago.
Working on a project where it requires me to have a password field using pattern attribute.
Not really done a lot of regex stuff and was wondering whether someone could help out.
The requirements for the field are as follows:
Can't contain the word "password"
Must be 8-12 in length
Must have 1 upper case
Must have 1 lower case
Must have 1 digit
Now, so far I have the following:
[^(password)].(?=.*[0-9])?=.*[a-zA-Z]).{8,12}
This doesn't work. We can get it so everything else works, apart from the password string being matched.
Thanks in advance,
Andy
EDIT: the method we've used now (nested in comments below) is:
^(?!.*(P|p)(A|a)(S|s)(S|s)(W|w)(O|o)(R|r)(D|d)).(?=.*\d)(?=.*[a-zA-Z]).{8,12}$
Thanks for the help
Use a series of anchored look aheads for the :must contain" criteria:
^(?!.*(?i)password)(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,12}$
I've added the "ignore case" switch (?i) to the "password" requirement, so it will reject `the word no matter the case of the letters.
This regex should to the job:
^(?!.*password)(?=.*\d)(?=.*[A-Z])(?=.*[a-z]).{8,12}$
it will match:
^ // from the beginning of the input
(?!.*password) // negative lookbehind whether the text contains password
(?=.*\d+) // positive lookahead for at least one digit
(?=.*[A-Z]+) // positive lookahead for at least one uppercase letter
(?=.*[a-z]+) // positive lookahead for at least one lowercase letter
.{8,12} // length of the input is between 8 and 12 characters
$
Link to phpliveregex
Try This:
^(?!.*password)(?=.*[A-Z])(?=.*[0-9])(?=.*[a-z]).{8,12}$
Explanation
^ Start anchor
(?=.*[A-Z]) Ensure string has one uppercase letter
(?=.*[0-9]) Ensure string has one digits.
(?=.*[a-z]) Ensure string has one lowercase letter
{8,12} Ensure string is of length 8 - 12.
(?!.*password) Not of word password
$ End anchor.
Try this way
Public void validation()
string xxxx = "Aa1qqqqqq";
if (xxxx.ToUpper().Contains("password") || !(xxxx.Length <= 12 & xxxx.Length >= 8) || !IsMatch(xxxx, "(?=.*[A-Z])") || !IsMatch(xxxx, "(?=.*[a-z])") || !IsMatch(xxxx, "(?=.*[0-9])"))
{
throw new System.ArgumentException("Your error message here", "Password");
}
}
public bool IsMatch(string input, string pattern)
{
Match xx = Regex.Match(input, pattern);
return xx.Success;
}
I have a requirement for password rules. Following are the rules.
The password must follow the following guidelines:
Be at least eight characters long
Contain 3 of these 4 options: lower case letter, upper case letter, number, or special character
When user specifies a password that does not meet the above rules, return message stating:
Password must be at least 8 characters long and contain 3 of the 4 following options:
Lower case letter (a-z)
Upper case letter (A-Z)
Number (0-9)
Special character (!##$%^&')
Please help me to get a regex expression to handle above conditions.
i appreciate all your help. following is the solution for my requirement
if(password.matches("^(?=.*[0-9]).{1,}$")){
validCount++;
}
if(password.matches("^(?=.*[a-z]).{1,}$")){
validCount++;
}
if(password.matches("^(?=.*[A-Z]).{1,}$")){
validCount++;
}
if(password.matches("^(?=.*[##$%^&+=]).{1,}$")){
validCount++;
}
return validCount >= 3 ? true : false;
Thanks,
Ramki
This is, if you want an elegant regex, as close as you can get
^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[!##$%^&'])[^ ]{8,}$
The basic idea is to use a technique called "positive lookahead" :
(?=.*PutHereWhatYouWantToAllow)
Your extra requirement 3 out of 4 is not easy to solve with regexes cause you cannot make them count basically.
You could write out the necessary permutations of the above regex (tell me if it doesn't make sense) but that would make a very long regex.
What you could do is write out the permutations in code so that the regex stays maintainable since you are not repeating the patterns literally.
I'll have a shot if I you tell me your language (C#?) cause it's a good challenge.
Update 1
Here is the regex that will match at least 3 of your requirements (4 is also allowed), just for the challenge of it. Don't use this in production but loop in the language with individual regexes as mentioned in the comments.
^((?=.[a-z].[A-Z].[\d])|(?=.[a-z].[\d].[A-Z])|(?=.[A-Z].[a-z].[\d])|(?=.[A-Z].[\d].[a-z])|(?=.[\d].[a-z].[A-Z])|(?=.[\d].[A-Z].[a-z])|(?=.[a-z].[A-Z].[!##$%^&'])|(?=.[a-z].[!##$%^&'].[A-Z])|(?=.[A-Z].[a-z].[!##$%^&'])|(?=.[A-Z].[!##$%^&'].[a-z])|(?=.[!##$%^&'].[a-z].[A-Z])|(?=.[!##$%^&'].[A-Z].[a-z])|(?=.[a-z].[\d].[!##$%^&'])|(?=.[a-z].[!##$%^&'].[\d])|(?=.[\d].[a-z].[!##$%^&'])|(?=.[\d].[!##$%^&'].[a-z])|(?=.[!##$%^&'].[a-z].[\d])|(?=.[!##$%^&'].[\d].[a-z])|(?=.[A-Z].[\d].[!##$%^&'])|(?=.[A-Z].[!##$%^&'].[\d])|(?=.[\d].[A-Z].[!##$%^&'])|(?=.[\d].[!##$%^&'].[A-Z])|(?=.[!##$%^&'].[A-Z].[\d])|(?=.[!##$%^&'].[\d].[A-Z]))[^ ]{8,}$
Update 2
This is the approach to take in java
From the comments I read that you are testing like the following
lowercase "^[a-z]*$";
uppercase "^[A-Z]*$";
digits="^[0-9]*$";
I don't think you are on the right track here. The lowercase will only report success if all characters are lowercase, and not just one. Same remark for the rest.
These are the 4 individual regexes of which at least 3 should report a match
[a-z]
[A-Z]
\d
[!##$%^&']
Here is the test that the password should not contain a space
^[^ ]*$
The test for at least 8 characters
.{8,}
So I split the requirements and not combine them. This should make for more readable code especially if one starts with regexes.
Here's how I would do it:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePassword
{
public static void main (String[] args)
{
String pw = "abaslkA3FLKJ";
// create an array with 4 regex patterns
Pattern [] patternArray = {
Pattern.compile("[a-z]"),
Pattern.compile("[A-Z]"),
Pattern.compile("[0-9]"),
Pattern.compile("[&%$#]")
};
int matchCount = 0;
// iterate over the patterns looking for matches
for (Pattern thisPattern : patternArray) {
Matcher theMatcher = thisPattern.matcher(pw);
if (theMatcher.find()) {
matchCount ++;
}
}
if (matchCount >= 3) {
System.out.println("Success");
}
else {
System.out.println("Failure: only " + matchCount + " matches");
}
}
}
I only added a few special characters to the 4th pattern... You'll have to modify it for your needs. You may need to escape certain characters with a backslash. You may also want to add other constraints like checking for no spaces. I'll leave that up to you.