how to manage in JavaScript null values from PHP code

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.");
    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.


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

Need Your Help

How to inherit from the DbContext Class

c# entity-framework

I am working on MVC and in the model I created a class that uses Entity