Skip to content

How to check if input value is an image or not?

I’m trying to take the input string and verify whether an image exists on the URL.

When I click the ‘Check’ button, the intended result is to validate whether the input value is a regex match. If it is or is not, display an appropriate result.

JS

checkImage.addEventListener("click", function () {
  let url = document.getElementById("inputUrl").value;
  // console.log(url);

  if (typeof url !== "string") result.textContent = "This is not an image";
  return url.match(/.(jpg|jpeg|gif|png)$/) != null;

  result.textContent;
});

checkImage.addEventListener("click", function () {
  let url = document.getElementById("inputUrl").value;
  // console.log(url);

  if (typeof url !== "string") result.textContent = "This is not an image";
  return url.match(/.(jpg|jpeg|gif|png)$/) != null;

  result.textContent;
});
<form action="">
  <input type="text" id="inputUrl" placeholder="url of image">
  <button type="button" id="checkImage">Check</button>
</form>

<h3 id="result">?</h3>

Answer

You’re returning from the event handler before anything is put in the result div.

A few other notes.

  • using regex.test() is the appropriate method for testing if a string matches a pattern. The match method you used, although it will work, is intended for extracting parts of a string.
  • Your url variable will always be a string as the value of an input, so checking that is unnecessary.

var checkImage = document.getElementById("checkImage");
var result = document.getElementById("result");

checkImage.addEventListener("click", function () {
  let url = document.getElementById("inputUrl").value;
  var is_image =  /.(jpg|jpeg|gif|png)$/.test(url);
  result.textContent = is_image ? 'valid image' : 'invalid';
});
<form action="">
  <input type="text" id="inputUrl" placeholder="url of image">
  <button type="button" id="checkImage">Check</button>
</form>

<h3 id="result">?</h3>