JFFF
JFFF

Reputation: 989

Check if input contains 8 chars min, 1 digit and 1 letter minimum

Here's what I tried... It works if I only check if the value of the input is lesser than 8, but doesn't work to check if it contains at least 1 letter and 1 digit. What am I doing wrong ? =/

$(document).ready(function() {

var jVal = {
    'passWord' : function() {

        $('body').append('<div id="nameInfo" class="info"></div>');

        var nameInfo = $('#nameInfo');
        var ele = $('#password');
        var pos = ele.offset();
        ra = /^[A-Za-z]+$/;
        re = /^[0-9]+$/;

        nameInfo.css({
            top: pos.top - 3,
            left: pos.left + ele.width() + 15
        });

        if (ele.val().length < 8 & re.test(ele.value) & ra.test(ele.value)) {
            jVal.errors = true;
            nameInfo.removeClass('correct').addClass('error').html('&larr; too short').show();
            ele.removeClass('normal').addClass('wrong');
        }

        else {
            nameInfo.removeClass('error').addClass('correct').html('&radic;').show();
            ele.removeClass('wrong').addClass('normal');
        }
    }

}
$('#password').change(jVal.passWord);
});

Upvotes: 0

Views: 1264

Answers (2)

Dan Breen
Dan Breen

Reputation: 12924

You could use a single regex to do everything:

/^(?=.*\d.*)(?=.*[a-z].*)\w{8,}$/i

The first two pieces check for both a digit, and an a-z char in the whole string, and then the last piece ensures it's at least 8 characters. You could change the last \w to . to allow special chars if so desired.

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

ra checks if the password is made ENTIRELY of letters. re checks if the password is made ENTIRELY of numbers. They are mutually exclusive and therefore cannot both be true.

Instead, use ra = /[a-z]/i; re = /[0-9]/;.

EDIT: Also, since you're using jQuery, you should be testing on ele.val(), not ele.value.

Upvotes: 6

Related Questions