Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

264
Visualizações
How to handle image required field in case of update, react js

I am using react hook form to upload a file, and my file upload field is:

<input
    className={`form-control ${
        errors["cover_image"] ? "border-red-500" : ""
    }`}
    type="file"
    id="cover_image"
    {...register("cover_image")}
    onChange={handleChange}
/>

and I have yup validation as:

cover_image: Yup.mixed()
    .test("name", "Cover Image is required", (value) => {
        return value[0] && value[0].name !== "";
    })
    .test("fileSize", "File must be less than 2MB", (value) => {
        return value[0] && value[0].size <= 2000000;
    })
    .test("type", "Only image are supported", (value) => {
        return value[0] && value[0].type.includes("image");
    }),

It is working fine in the case of creating a page, it shows required, when not uploaded, but in the case of the edit page, it is showing a field is required, if I don't upload any file. There is a file value on item.cover_image.

I have also tried defaultValue={item.cover_image}, but it is not allowing to set me default value in case of edit. How would be the best way to handle this situation?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Instead of using an external package to validate I would recommend using validation of react-hook-form

import { useForm } from 'react-hook-form'

export default function App() {
  const { register, handleSubmit, formState } = useForm()

  console.log({ errors: formState.errors })

  return (
    <form onSubmit={handleSubmit(data => console.log(data))}>
      <input
        type="file"
        {...register('cover_image', {
          validate: value => {
            const isExists = !!value.length
            const isGoodSize = value[0] && value[0].size <= 2000000
            const isImageType = value[0] && value[0].type.includes('image')

            if (!isExists) return "Cover Image is required"
            if (!isGoodSize) return 'File must be less than 2MB'
            if (!isImageType) return 'Only image are supported'

            return undefined
          }
        })}
      />

      <input type="submit" />
    </form>
  )
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda