0

I have made a web app where you can upload images via an image url. Here is the link: https://meme-gallery-web-app.netlify.app/

The problem is if I press the submit button where the form is empty, it still posts an empty image data to database.

My question is how can I activate the button only when there's a proper image ur? Only when a proper image url is submitted in the form, then the button will activate and I can submit it. Here is the code where I handle the form request.

import { FormControl, Input, Button } from "@chakra-ui/react";
import axios from "axios";
import React from "react";
import { baseUrl } from "../config";

class SubmitLink extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      url: "",
    };
  }

  onInputChange = (event) => {
    this.setState({
      url: event.target.value,
    });
  };
// where I make post request. 
  onClick = () => {
    axios
      .post(`${baseUrl}/submitlink`, {
        url: this.state.url,
      })
      .then((response) => {
        console.log(response);
        this.props.onSuccessfulUpload();
        this.setState({
          url: "",
        });
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  render() {
    return (
      <FormControl>
        <Input
          type='url'
          value={this.state.url}
          onChange={this.onInputChange}
          width={{
            base: "70%",
            md: "55%",
            xl: "60%",
          }}
          ml={{
            base: "5%",
            md: "5%",
            xl: "4%",
          }}
        />
        <Button
          ml={2}
          mb={1}
          colorScheme='teal'
          type='submit'
          onClick={this.onClick}
          size='md'
        >
          Submit
        </Button>
      </FormControl>
    );
  }
}

export default SubmitLink;

here's the API where I handle the post request

// post api for saving images from URL

const imageModel = require("../models/models.js");

//ignore the date variables. haven't properly implemented it. 
var date = new Date();
var currentDate = date.toLocaleDateString();

const submitLink = async (req, res) => {
  let saveImageFromUrl = new imageModel();
  saveImageFromUrl.img.data = req.body.url;
  saveImageFromUrl.postedAt = currentDate;
  await saveImageFromUrl.save(function (err, result) {
    if (err) return console.error(err);
    else {
      res.sendStatus(202);
    }
  });
};

module.exports = submitLink;

3
  • You can add the attribute disabled to the button until the URL field is not empty. You can (and probably should) validate the URL in your upload script too. Checking the length is not 0 is the first step. Then maybe a header request to make sure the link returns an image and not a 404.
    – Liftoff
    Sep 13, 2021 at 5:37
  • should I validate the URL using regex? Sep 13, 2021 at 5:40
  • You certainly can. That is a good step as well.
    – Liftoff
    Sep 13, 2021 at 5:42

1 Answer 1

1

You could disable the button while checking if the url is valid or not

Something like this:

const isUrlValid = () => {
  const { url } = this.state;
  const res = url.match(
    /(http(s)?:\/\/.)?(www\.)?[\w#%+.:=@~-]{2,256}\.[a-z]{2,6}\b([\w#%&+./:=?@~-]*)/g
  );
  if (res == null) return false;
  return true;
};

//...JSX Body

<Button
  ml={2}
  mb={1}
  colorScheme="teal"
  type="submit"
  onClick={this.onClick}
  size="md"
  disabled={isUrlValid()}
>
  Submit
</Button>;

7
  • can you explain the regex part? I didn't practice it often. Sep 13, 2021 at 5:51
  • Using new URL is simpler than a regex
    – mplungjan
    Sep 13, 2021 at 5:58
  • @mplungjan how to do that? Sep 13, 2021 at 6:08
  • @tanjimanim, It's a regex to check if the URL matches that. For detail explaination, you could go here
    – Ryan Le
    Sep 13, 2021 at 6:11
  • 1
    @mplungjan is right, there is another way to check if URL valid, you could have a reference here
    – Ryan Le
    Sep 13, 2021 at 6:12

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.