How to get validation error on input element in React if the input is of type="file"

Viewed 399

I am using material ui and covering the input component with icons but as I have an input element hidden I am not getting any validation error. i am using useForm for validation

<IconButton variant="contained" component="label">
  <AddCircleOutlineIcon fontSize="large" />
  <input
    {...register("image", { required: true })}
    required
    type="file"
    accept=".jpg,.png,.jpeg"
    onChange={(e) => setFile(e.target.files[0])}
    hidden
  />
</IconButton>
1 Answers

You will have to use validate function to validate required file extension still works.

const Upload = () => {
  let [file, setFile] = useState(null);
  /**
   * Create a new state variable to hold the name of the
   * file. This is needed since the browser does not retain
   * the filename by default when uploading. 
   */
  let [filename, setFilename] = useState('');

  const filterBySize = (file) => {
    //filter out files larger than 5MB
    return file.size < 5242880;
  };

  const fileChangedHandler = event => {
    let file = event.target.files[0];
    let reader = new FileReader();
    /**Capture filename */
    setFilename(file.name);
    console.log(file);
    reader.onload = function(e) {

      setFile(e.target.result);
    };
    reader.readAsDataURL(event.target.files[0]);

    if (file != ".png" || file !=".jpg" ) {
      window.alert("File does not support. You must use .png or .jpg ");
      return false;
   }
   if (file.size > e6) {
     window.alert("Please upload a file smaller than 1 MB");
     return false;
   }
   
  };
return(
  <input className="btn btn-secondary" 
                  id="fileInput" 
                  type="file" 
                  accept="image/*"
                  // inputProps={{ accept: 'image/*' }}
                  // fileFilter={filterBySize}
                  onChange={fileChangedHandler} 
                />

Ref : https://github.com/react-hook-form/react-hook-form/discussions/1946

Related