简体   繁体   中英

Input validation not detecting empty value

So I have an issue where I need to make my code when the mouse leaves an input field and the input field is either empty or has less than 5 characters it outputs something

I have tried putting .value after the getelementbyid. Please know that I can't use a button to submit the form.

var username = document.getElementById('username');
var user_length = username.length;

username.onmouseout = function(){
    if(username == ""){
        alert('hi');
        // var username_value = 
        //document.getElementById("username_output");
        // username_value.innerHTML ="Please fill in your username!";
        // username_value.style.color = 'red';
    }

    else if(user_length < 5){
        alert('smaller than 5');
    }
    else{
        alert('else');
    }
};

Whenever the mouse leaves it should output something. For some reason it's only going in the else statement not the other statements

You're comparing the input itself (the DOM element, the result of document.getElementById('username') ) with a string, not the input's value .

You want its value property:

if (username.value == "") {

But note that the user might type in a space, in which case the above would be false because " " is not equal to "" . You can use trim to fix that:

if (username.value.trim() == "") {

Since empty strings are falsy ¹, you can also save some typing:

if (!username.value.trim()) {

¹ "falsy" - Any JavaScript value that coerces to false when used as a boolean is called a falsy value. The falsy values are 0 , "" , NaN , null , undefined , and of course, false ; all other values are truthy .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM