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.

2
  • 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? Commented Jun 3, 2016 at 9:23
  • See Reference - Password Validation Commented Jan 14, 2021 at 15:05

4 Answers 4

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,}$
Sign up to request clarification or add additional context in comments.

Comments

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 _

Comments

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}

Comments

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>')
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.