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;

mplungjan
  • 169,008
  • 28
  • 173
  • 236
tanjim anim
  • 337
  • 3
  • 23
  • 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 '21 at 05:37
  • should I validate the URL using regex? – tanjim anim Sep 13 '21 at 05:40
  • You certainly can. That is a good step as well. – Liftoff Sep 13 '21 at 05:42

1 Answers1

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>;

Ryan Le
  • 7,708
  • 1
  • 13
  • 23