Home > Back-end >  using condition in jquery onclick button
using condition in jquery onclick button

Time:01-08

Im trying to confirm if the password strength is strong or weak and is the password is strong and when I submit it should have alert message like "You Have Strong Password" and when its weak "Invalid Password"

This is what I am now.

function checkPasswordStrength() {
        var passwordStrength = false;
        var number = /([0-9])/;
        var alphabets = /([a-zA-Z])/;
        var special_characters = /([~,!,@,#,$,%,^,&,*,-,_, ,=,?,>,<])/;
        if ($('#password').val().length < 8) {
            $('#password-strength-status').removeClass();
            $('#password-strength-status').addClass('weak-password');
            $('#password-strength-status').html("Weak (should be atleast 8 characters.)");
        } else {
            if ($('#password').val().match(number) && $('#password').val().match(alphabets) && $('#password').val().match(special_characters)) {
                $('#password-strength-status').removeClass();
                $('#password-strength-status').addClass('strong-password');
                $('#password-strength-status').html("Strong");
                return passwordStrength = true;
            } else {
                $('#password-strength-status').removeClass();
                $('#password-strength-status').addClass('medium-password');
                $('#password-strength-status').html("Medium (should include alphabets, numbers and special characters.)");
            }
        }
    }

    $('#btn-submit').click(function () {
        if (passwordStrength == false) {
        alert("INVALID PASSWORD");
        } else {
        alert("You have Strong PASSWORD");
        }

</script>

its for Educational Purpose only im just starting jquery.. thank you in advance..

CodePudding user response:

It looks like the variable scope is incorrect. var passwordStrength should be put outside of the checkPasswordStrength function.

var passwordStrength
function checkPasswordStrength() {

    ....

CodePudding user response:

You need to call the function instead of just checking your variable. So rather do

$('#btn-submit').click(function () {
    if (checkPasswordStrength() === false) {

instead of

$('#btn-submit').click(function () {
    if (passwordStrength == false) {

Then, instead of return passwordStrength = true; you should do just passwordStrength = true and add a return passwordStrength to the very end of your function so it will return either false or true.

  •  Tags:  
  • Related