Regex password validator - regex

I have the following rules for password validation:
at least 6 characters
at least 1 capital letter
How can I validate this with a RegEx?
Here is my pattern: ^(?=.*[0-9]+.*)(?=.*[a-zA-Z]+.*)[0-9a-zA-Z]{6,}$
The pattern above enforces also numbers ... which I don't need. However user can enter any other characters he/she wishes except that must contain one capital and be longer or equal to 6 characters.

You can try this:
^(?=.*?[A-Z]).{6,}$
DEMO
If you want to allow special characters as well then change it like
^(?=.*?[A-Z])(?=.*?[#?!#$%^&*-]).{6,}$

^(?=.*[A-Z])[\w-[_\]]{6,}$
This force to contains a capital letter with (?=.*[A-Z]) and allow alphanumeric : [\w-[_\]] (\w is [a-zA-Z0-9_] in which we remove the _

You can use this :
(?=.*[A-Z]).{8}
or If you want to full rule, can try this :
(?=[a-z]*[A-Z])(?=\D*\d)(?=.*[#?!#$%^&*-]).{8}

It might be better to evaluate the rules separately to provide feedback to user as to which rule failed to validate.
I suggest doing something like this instead: https://jsfiddle.net/hejecr9d/
// will store list of rules
var rules = []
// at least one capital letter rule
rules.one_capital_letter = {
fail_message: 'password needs at least one capital letter',
validate: function(password){
return /[A-Z]/.test(password)
}
}
// at least six letters rule
rules.at_least_six_letters = {
fail_message: 'password needs to have at least 6 characters',
validate: function(password){
return password.length >= 6
}
}
function validate_password(password) {
// goes through all the rules
for(rule in rules) {
if(!rules[rule].validate(password)) {
return {success: false, message: rules[rule].fail_message}
}
}
// return success after all rules are checked
return {success: true, message: 'password validated successfully'}
}
// Test if it works
var test_strings = ['abcd', 'Abcd', 'Abcdef']
for(i in test_strings) {
$('body').append(test_strings[i] + ': ' + validate_password(test_strings[i]).message + '<br>')
}

Related

Testing for n lowercase characters in a string using a regex?

Trying to create a regular expression that tests for n lowercase characters in a string.
So for a minimum of 2 characters for example, I thought something like ([a-z]){2,} might work.
For the below test the first two are expected to pass:
const min = 2;
const tests = ['a2a#$2', 'a2a#$2a2', 'a2'];
const regex2: RegExp = new RegExp(`([a-z]){${min},}`);
tests.forEach((t) => {
const valid = regex2.test(t);
console.log(`t: ${t} is valid: ${valid}`);
});
Thoughts?
[a-z].*[a-z]
Looks for lowercase, then anything or nothing in between, then lowercase again.
Try it out for yourself:
https://www.debuggex.com/
I might go the route of first stripping off all characters other than lowercase letters, then using a length assertion:
var min = 2;
var tests = ['a2a#$2', 'a2a#$2a2', 'a2'];
tests.forEach(e => {
if (e.replace(/[^a-z]+/g, "").length >= min) {
console.log("MATCH: " + e);
}
else {
console.log("NO MATCH: " + e);
}
});
This isn't the most scalable solution, but for 2 lowercase letters, you could do this: .*[a-z].*[a-z].*. Of course, this breaks down if you want to match 1000 lower case letters, you'd have to type [a-z] 1000 times.
To test if the string has exactly n lower-case letters, attempt to match the following regular expression:
^[^a-z]*(?:[a-z][^a-z]*){n}$
where n is replaced with the desired value.
See Demo for n = 9.
To match at least n lower-case letters use
[^a-z]*(?:[a-z][^a-z]*){n,}
From the below, the match function will return the matches array. If there are no matches then it will return null. you can use matches.length to filter the array.
const min = 2;
const tests = ['a2a#$2', 'a2a#$2a2', 'a2'];
tests.forEach((t) => {
const matches = t.match(/([a-z])/g)||[];
console.log(`t: ${t} is valid: ${matches.length}`);
});

Regex Issue in Swift [duplicate]

This question already has answers here:
Match exact string
(3 answers)
Closed 6 years ago.
I am working on a username regex where the only characters that are accepted are a-z, A-Z, 0-9, and _. The current max length of the username is 18 characters with a minimum of one. My current regex is below.
let regexCorrectPattern = "[a-zA-Z0-9_]{1,18}$"
I am having the following issue. Special characters added anywhere but the end of the string allow the regex to pass. For example
jon! FAIL
!jon PASS
j!on PASS
The method I am using to test the regex is below along with the calling method. Any input would be greatly appreciated.
Regex Testing Method
func regexTestString(string: String, withPattern regexPattern: String) -> Bool
{
// This method is used for all of the methods below.
do
{
// Create regex and regex range.
let regex = try NSRegularExpression(pattern: regexPattern, options: .CaseInsensitive)
let range = NSMakeRange(0, string.characters.count)
// Test for the number of regex matches.
let numberOfMatches = regex.numberOfMatchesInString(string, options: [], range: range)
// Testing Code.
print(numberOfMatches)
// Return true if the number of matches is greater than 1 and return false if the number of mathces is 0.
return (numberOfMatches == 0) ? false : true
}
catch
{
// Testing Code
print("There is an error in the SignUpViewController regexTestString() method \(error)")
// If there is an error return false.
return false
}
}
Calling Method
func usernameTextFieldDidEndEditing(sender: AnyObject)
{
let usernameText = self.usernameField.text!.lowercaseString
let regexCorrectPattern = "[a-zA-Z0-9_]{1,18}$"
let regexWhitespacePattern = "\\s"
let regexSpecialCharacterPattern = ".*[^A-Za-z0-9].*"
if regexTestString(usernameText, withPattern: regexCorrectPattern)
{
// The regex has passed hide the regexNotificationView
}
else if regexTestString(usernameText, withPattern: regexWhitespacePattern)
{
// The username contains whitespace characters. Alert the user.
}
else if regexTestString(usernameText, withPattern: regexSpecialCharacterPattern)
{
// The username contains special characters. Alert the user.
}
else if usernameText == ""
{
// The usernameField is empty. Make sure the sign up button is disabled.
}
else
{
// For some reason the Regex is false. Disable the sign up button.
}
}
You want the entire string to contain only the characters you specified, so all you need is to add ^ at the start of the pattern:
^[a-zA-Z0-9_]{1,18}$

as3 regular expression to validate a password

I have a form that asks for a password and I want to validate if the password has at least eight characters, and of these eight characters at least two must be numbers and two must be letters in any order. I'm trying with this:
function validatePassword():void
{
var passVal:String = pass.text;
if(validPass(passVal))
{
trace("Password Ok");
sendForm();
}
else
{
trace("You have entered an invalid password");
}
function validPass(passVal:String):Boolean{
var pw:RegExp = /^?=.{8,}[A-Za-z]{2,}[0-9]{2,}/;
return(pw.test(passVal));
}
}
But it doesn't work. What I'm doing wrong?
Any help would be really appreciated!
use this pattern ^(?=.{8})(?=(.*\d){2})(?=(.*[A-Za-z]){2}).*$
^ anchor
(?=.{8}) look ahead for at least 8 characters
(?=(.*\d){2}) look ahead for at least 2 digits in any order
(?=(.*[A-Za-z]){2}) look ahead for at least 2 letters in any order
.*$ catch everything to the end if passed previous conditions
The problem is that your regex is forcing the numbers to follow the letters ([A-Za-z]{2,}[0-9]{2,}). While it is possible to write such a regex, I suggest using a simple length check and two regexes:
function validPass(passVal:String):Boolean{
if (passVal.length < 8)
return False;
var letterRegex:RegExp = /^.*?[A-Za-z].*?[A-Za-z].*?$/;
var numberRegex:RegExp = /^.*?\d.*?\d.*?$/;
return letterRegex.test(passVal) && numberRegex.test(passVal);
}

Regex to validate passwords with characters restrictions

I need to validate a password with these rules:
6 to 20 characters
Must contain at least one digit;
Must contain at least one letter (case insensitive);
Can contain the following characters: ! # # $ % & *
The following expression matches all but the last requirement. What can I do with the last one?
((?=.*\d)(?=.*[A-z]).{6,20})
I'm not completely sure I have this right, but since your last requirement is "Can contain the following characters: !##$%&*" I am assuming that other special characters are not allowed. In other words, the only allowed characters are letters, digits, and the special characters !##$%&*.
If this is the correct interpretation, the following regex should work:
^((?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!##$%&*]{6,20})$
Note that I changed your character class [A-z] to [a-zA-Z], because [A-z] will also include the following characters: [\]^_`
I also added beginning and end of string anchors to make sure you don't get a partial match.
^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!##$%&*]{6,20}$
Regex could be:-
^(?=.*\d)(?=.*[a-zA-Z])[a-zA-Z0-9!##$%&*]{6,20}$
How about this in Javascript:-
function checkPwd(str) {
if (str.length < 6) {
return("too_short");
} else if (str.length > 20) {
return("too_long");
} else if (str.search(/\d/) == -1) {
return("no_num");
} else if (str.search(/[a-zA-Z]/) == -1) {
return("no_letter");
} else if (str.search(/[^a-zA-Z0-9\!\#\#\$\%\^\&\*\(\)\_\+]/) != -1) {
return("bad_char");
}
return("ok");
}
Also check out this

Reg expression validate / \ # & characters

I've been learning how Regular expressions work, which is very tricky for me. I would like to validate this chars below from input field. Basically if string contains any of these characters, alert('bad chars')
/
\
#
&
I found this code, but when I change it around doesn't seem to work. How can I alter this code to meet my needs?
var str = $(this).val();
if(/^[a-zA-Z0-9- ]*$/.test(str) == false) {
alert('bad');
return false;
} else {
alert('good');
}
/^[a-zA-Z0-9- ]*$/ means the following:
^ the string MUST start here
[a-zA-Z0-9- ] a letter between a and z upper or lower case, a number between 0 and 9, dashes (-) and spaces.
* repeated 0 or more times
$ the string must end here.
In the case of "any character but" you can use ^ like so: /^[^\/\\#&]*$/. If this matches true, then it doesn't have any of those characters. ^ right after a [ means match anything that isn't the following.
.
You could just try the following:
if("/[\\/#&]/".test(str) == true) {
alert('bad');
return false;
} else {
alert('good');
}
NOTE: I'm not 100% on what characters need to be escaped in JavaScript vs. .NET regular expressions, but basically, I'm saying if your string contains any of the characters \, /, # or &, then alert 'bad'.