0

I have the next PHP/HTML code for upload an image:

<label>Image (*)</label>
<!-- if image exists, show it -->
<?php if($category->getImage() === null) : ?>
    <input type="file" name="image" id="image" required>
<?php else : ?>
    <p><img src="../uploads/images/<?php echo $categoria->getImage(); ?>"></p>
    <input type="file" name="image" id="image">
<?php endif; ?>

And I want to validate it using JavaScript

// Validate image
image = document.getElementById("image").value;
if (!image) {
    window.alert("You must select a file for the image.");
    document.getElementById("image").focus();
    return false;
}

The image is required. If you create a new registry it sets all of its atributes to null, including the image. Then, the image is not show and you can set it in the form. If you want to update them, the form shows the current imagen but you don't have to update it if you don't want to.

I need to validate if the file hasn't been uploaded and the value is null it means that the user is creating a new registry and the image is required. If the file hasn't been uploaded but its value isn't null, the user is updating the registry and it isn't required to upload an image.

Thanks in advance and sorry for my bad english.

1 Answer 1

1

You can add id to the image

<img id="foo" src="../uploads/images/<?php echo $categoria->getImage(); ?>">

and check if it's in the DOM:

if ($('#foo').length) {
    // image is there
}

or without jQuery:

if (document.getElementById("foo")) {
    // image is there
}
Sign up to request clarification or add additional context in comments.

3 Comments

I've tried it out but it doesn't work for me. I can't get the value of foo on: foo = document.getElementById("foo").value; I think it is because the script is before the img, then of course the img doesn't exist yet, and that doesn't work. The script is in the form tag.
@user3116721 you can validate the form on submit.
Awesome!! The version without jQuery worked fine for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.