Veske
Veske

Reputation: 557

Checking if the input is a number or something else

So I am trying to check if a string in a variable has numbers inside of it or not.

This is the code I use to go over the variable:

function checkIfOk(pass){
    for (var i=0; i<pass.length; i++) {
        if(/[0-9]/.test(pass)){
            console.log("Number: "+pass[i]);
        }else{
            console.log("Letter: "+pass[i]);
        }
    }
}

This code is invoked by this:

$(document).ready(function() {
    $(".PWD1").on("keypress keyup", function() {
        var pass = $(this).val();
        $("#check").text(checkIfOk(pass));
    });
});

So it reads a string from a password field and then goes over every element in that string with a for loop. It will check with the IF statement, if the pass[i] is a number from 0-9, if it is it will print to console Number: x.

But for some reason, the else statement is working only when I have no numbers in my string, when a number is inserted, the for loop will accept all elements as numbers and disregard my else statement. Why is that?

Upvotes: 0

Views: 53

Answers (1)

Surendheran
Surendheran

Reputation: 197

Try this code,

function checkIfOk(pass){
    var status = "";
 for (var i=0; i<pass.length; i++) {
    status = isNan(pass[i]);
    if(status==false){
        console.log("Number: "+pass[i]);
    }else{
        console.log("Letter: "+pass[i]);
    }
 }
}

Upvotes: 2

Related Questions