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.toLo开发者_开发问答werCase();
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.
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.
EDIT, from the comments, you said the file name was text.PNG. "PNG" is not the same as "png"
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))
{
}
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>
精彩评论