1

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.

user2818430
  • 5,853
  • 21
  • 82
  • 148
  • Where did you test for a capital letter? It seems you are testing for at least one digit and at least one letter, and that only digits and letters are allowed... Seems not related to your requirements. Which is it? – trincot Jun 03 '16 at 09:23
  • See [Reference - Password Validation](https://stackoverflow.com/questions/48345922/reference-password-validation/48346033#48346033) – ctwheels Jan 14 '21 at 15:05

4 Answers4

1

You can try this:

^(?=.*?[A-Z]).{6,}$

DEMO

If you want to allow special characters as well then change it like

^(?=.*?[A-Z])(?=.*?[#?!@$%^&*-]).{6,}$
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
0
^(?=.*[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 _

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
0

You can use this :

(?=.*[A-Z]).{8}

or If you want to full rule, can try this :

(?=[a-z]*[A-Z])(?=\D*\d)(?=.*[#?!@$%^&*-]).{8}
Arip H
  • 67
  • 1
  • 10
0

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>')
}
Martin Gottweis
  • 2,721
  • 13
  • 27