Khurram Ijaz
Khurram Ijaz

Reputation: 1864

Why I can not do “or” in my JavaScript if condition?

Hi I have following function which behaves differently when I add an OR condition in it.

<script>
function checkfield(obj)
{
    var full_name = obj.upload_image.value.toLowerCase();
    var full_length = parseInt(full_name.length);
    var dotAt = parseInt(full_name.lastIndexOf("."));

    var ext = full_name.substring((dotAt+1), full_length);
    if(ext == "jpg" || ext == "png")
        {
            //alert("Sorry! allowed file types are .png, .gif, .jpg");
            //return false;
            console.log("Correct Extention");
        }
        else{
            console.log("Wrong extention");
        }


    return false;
}
</script>

What ever I give before the || operator it works fine and the second one fails. please can some one pick out what i am doing wrong or how this should be done.

Upvotes: 0

Views: 140

Answers (3)

hvgotcodes
hvgotcodes

Reputation: 120178

your conditional is fine, the problem is probably with the value in ext. I would console.log it or look at the value in the debugger, its probably not what you think it is.

enter image description here

EDIT, from the comments, you said the file name was text.PNG. "PNG" is not the same as "png"

Upvotes: 5

BrunoLM
BrunoLM

Reputation: 100322

If you use a regex you can validate multiple extensions in one line.

// allows: jpeg, jpg, png, gif
if (/\.(jpe?g|png|gif)$/i.test(full_name))
{
}

Upvotes: 3

Sahal
Sahal

Reputation: 4136

Try this

<script>
function checkfield(obj)
{
    var full_name = obj.upload_image.value.toLowerCase();
    var full_length = parseInt(full_name.length);
    var dotAt = parseInt(full_name.lastIndexOf("."));

    var ext = full_name.substring((dotAt+1), full_length);
    if(trim(ext) == "jpg" || trim(ext) == "png")
        {
            //alert("Sorry! allowed file types are .png, .gif, .jpg");
            //return false;
            console.log("Correct Extention");
        }
        else{
            console.log("Wrong extention");
        }


    return false;
}
</script>

Upvotes: -5

Related Questions