With multiple 'if else' statements, how do

2019-08-30 02:52发布

I have a list of validation requirements for password strength to help users set their passwords, and it's broken into parts so that I can mark each requirement as 'valid' once the user has inputted a valid value in the password input box. (So if they put in a password longer than 7 characters, the password length requirement notice turns green etc). This is working great.

Now, I want to say, if all of the 'if' statements are valid, allow the form to be submitted, otherwise, don't. After reading around, I've made a few attempts at achieving this by setting a variable retVal = true but I'm not quite sure how to use that so have failed in my attempts so far. I also considered doing something like, if all the requirements have the class valid, then allow form submit but that didn't seem like the correct way?

$('#form-password-change #input-password').keyup(function() {

    // set password variable

    var pwd = $(this).val();

    // validate the length

    if (pwd.length > 7) {
        $('#length').removeClass('invalid').addClass('valid');
    } else {
        $('#length').removeClass('valid').addClass('invalid');
    }

    // RegExp
    // validate letter

    if ( /([^a-z]*[a-z]){3,}/i.test(pwd) ) {
        $('#letter').removeClass('invalid').addClass('valid');
    } else {
        $('#letter').removeClass('valid').addClass('invalid');
    }
});

2条回答
做个烂人
2楼-- · 2019-08-30 03:01

Try this:-

$('#form-password-change #input-password').keyup(function() {

var IsTrue=true;

// set password variable

var pwd = $(this).val();

// validate the length

if (pwd.length > 7) {
    $('#length').removeClass('invalid').addClass('valid');
} else {
    $('#length').removeClass('valid').addClass('invalid');
   IsTrue=false;
}

// RegExp
// validate letter

if ( /([^a-z]*[a-z]){3,}/i.test(pwd) ) {
    $('#letter').removeClass('invalid').addClass('valid');
} else {
    $('#letter').removeClass('valid').addClass('invalid');
   IsTrue=false
}
return IsTrue;
});
查看更多
beautiful°
3楼-- · 2019-08-30 03:18

Try this:

$('#form-password-change #input-password').keyup(function() {

    // set password variable

    var pwd = $(this).val();

    var truetest = 1;
    // validate the length

    if (pwd.length > 7) {
        $('#length').removeClass('invalid').addClass('valid');    
    } else {
       $('#length').removeClass('valid').addClass('invalid');
        truetest = 0;
    }

    // RegExp
    // validate letter

    if ( /([^a-z]*[a-z]){3,}/i.test(pwd) ) {
         $('#letter').removeClass('invalid').addClass('valid');
    } else {
        $('#letter').removeClass('valid').addClass('invalid');
        truetest = 0;
    }

    if(truetest)
    {
        //Do your stuff here
    }
});
查看更多
登录 后发表回答