Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

262
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda