最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I validate a input type='file' in react-hook-form? - Stack Overflow

programmeradmin0浏览0评论

I am using react hook form for my project. How can i validate input type='file'? It should only accept pdf. It was successfully inserted into database now when i want that only pdf should should be allowed. I am using react hook form v7.If someone knows plz suggest me. Thanks in advance!

Here's my code

import React from 'react'

import { useForm } from 'react-hook-form';
import { ToastContainer, toast } from 'react-toastify';


export const Workshop = () => {
  const { register, handleSubmit, formState: { errors }, reset } = useForm();

  const onSubmit = async (data, e) => {

    const formData = new FormData();
    formData.append('workshop',data.workshop)
    formData.append('participants',data.participants)
    formData.append('startdate',data.startdate)
    formData.append('selectedfile',data.selectedfile[0])
    formData.append('establishmentdate',data.establishmentdate)
    console.log(data)
    reset()
    const requestOptions = {
      method: 'POST',
      // headers: { 'Content-Type': 'application/json' },
      body: formData
    };

    const response = await fetch("http://localhost:3001/workshop", requestOptions);
    try {
      if (response.status == 200) {
        toast.success("Successfully added");
      }
    }
    catch {
      toast.error("Invalid");
    }
    const jsonData = await response.json();
    console.log(jsonData)

    // toast.error("Invalid"); 


  };

  return (
    <div className="container ">
      <ToastContainer />
      <form onSubmit={handleSubmit(onSubmit)}>
        <div class="mb-3 mt-5" >
          <h2>Details of Workshops/Seminars
          </h2>
          <label for="exampleFormControlInput1" class="form-label">Name of the workshop/ seminar
          </label>
          <input type="text" class="form-control w-25" name="workshop" id="exampleFormControlInput1" {...register("workshop", { required: true, pattern:{value:/^[a-zA-Z]+$/ ,message:'Only characters allowed'}})} />
          {errors.workshop && errors.workshop.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.workshop && errors.workshop.type === "pattern" && (
        <div style={{color:'red'}}> Only characters allowed</div>
      )}
        </div>
        <div class="mb-3 w-25 ">
          <label for="exampleFormControlTextarea1" class="form-label">Number of Participants
          </label>
          <input type="text" class="form-control" id="exampleFormControlTextarea1" name="participants" {...register("participants", { required: true, pattern:{value:/^[0-9\b]+$/ ,message:'Only characters allowed'}})} />
          {errors.participants && errors.participants.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.participants && errors.participants.type === "pattern" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>
        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Date From – To
          </label>
          <input type="date" class="form-control" id="exampleFormControlTextarea1" name="startdate" {...register("startdate",{required:true})} />
          {errors.startdate && errors.startdate.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.startdate && errors.startdate.type === "valueAsDate" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>

        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Link to the Activity report on the website(Upload PDF)
          </label>
          <input type="file" class="form-control" id="exampleFormControlTextarea1" name="selectedfile" {...register('selectedfile', {
            required:true,
            
          })} />
          
        </div>
        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Date of establishment of IPR cell
          </label>
          <input type="date" class="form-control" id="exampleFormControlTextarea1" name="establishmentdate" {...register("establishmentdate",{required:true})} />
          {errors.establishmentdate && errors.establishmentdate.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.establishmentdate && errors.establishmentdate.type === "valueAsDate" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>

        <button type="submit" class="btn btn-primary me-md-2">Submit</button>
        <button type="button" class="btn btn-primary me-md-2" >Download Excel</button>
        <button class="btn btn-primary me-md-2" >Download PDF</button>
        <button class="btn btn-primary me-md-2" >Download Word</button>

      </form>
    </div>
  )
}

How should I fix this?

I am using react hook form for my project. How can i validate input type='file'? It should only accept pdf. It was successfully inserted into database now when i want that only pdf should should be allowed. I am using react hook form v7.If someone knows plz suggest me. Thanks in advance!

Here's my code

import React from 'react'

import { useForm } from 'react-hook-form';
import { ToastContainer, toast } from 'react-toastify';


export const Workshop = () => {
  const { register, handleSubmit, formState: { errors }, reset } = useForm();

  const onSubmit = async (data, e) => {

    const formData = new FormData();
    formData.append('workshop',data.workshop)
    formData.append('participants',data.participants)
    formData.append('startdate',data.startdate)
    formData.append('selectedfile',data.selectedfile[0])
    formData.append('establishmentdate',data.establishmentdate)
    console.log(data)
    reset()
    const requestOptions = {
      method: 'POST',
      // headers: { 'Content-Type': 'application/json' },
      body: formData
    };

    const response = await fetch("http://localhost:3001/workshop", requestOptions);
    try {
      if (response.status == 200) {
        toast.success("Successfully added");
      }
    }
    catch {
      toast.error("Invalid");
    }
    const jsonData = await response.json();
    console.log(jsonData)

    // toast.error("Invalid"); 


  };

  return (
    <div className="container ">
      <ToastContainer />
      <form onSubmit={handleSubmit(onSubmit)}>
        <div class="mb-3 mt-5" >
          <h2>Details of Workshops/Seminars
          </h2>
          <label for="exampleFormControlInput1" class="form-label">Name of the workshop/ seminar
          </label>
          <input type="text" class="form-control w-25" name="workshop" id="exampleFormControlInput1" {...register("workshop", { required: true, pattern:{value:/^[a-zA-Z]+$/ ,message:'Only characters allowed'}})} />
          {errors.workshop && errors.workshop.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.workshop && errors.workshop.type === "pattern" && (
        <div style={{color:'red'}}> Only characters allowed</div>
      )}
        </div>
        <div class="mb-3 w-25 ">
          <label for="exampleFormControlTextarea1" class="form-label">Number of Participants
          </label>
          <input type="text" class="form-control" id="exampleFormControlTextarea1" name="participants" {...register("participants", { required: true, pattern:{value:/^[0-9\b]+$/ ,message:'Only characters allowed'}})} />
          {errors.participants && errors.participants.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.participants && errors.participants.type === "pattern" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>
        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Date From – To
          </label>
          <input type="date" class="form-control" id="exampleFormControlTextarea1" name="startdate" {...register("startdate",{required:true})} />
          {errors.startdate && errors.startdate.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.startdate && errors.startdate.type === "valueAsDate" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>

        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Link to the Activity report on the website(Upload PDF)
          </label>
          <input type="file" class="form-control" id="exampleFormControlTextarea1" name="selectedfile" {...register('selectedfile', {
            required:true,
            
          })} />
          
        </div>
        <div class="mb-3 w-25">
          <label for="exampleFormControlTextarea1" class="form-label">Date of establishment of IPR cell
          </label>
          <input type="date" class="form-control" id="exampleFormControlTextarea1" name="establishmentdate" {...register("establishmentdate",{required:true})} />
          {errors.establishmentdate && errors.establishmentdate.type === "required" && (
        // <span role="alert">This is required</span>
        <div style={{color:'red'}}> This is required</div>
        
      )}
      
        {errors.establishmentdate && errors.establishmentdate.type === "valueAsDate" && (
        <div style={{color:'red'}}> Only numbers allowed</div>
      )}
        </div>

        <button type="submit" class="btn btn-primary me-md-2">Submit</button>
        <button type="button" class="btn btn-primary me-md-2" >Download Excel</button>
        <button class="btn btn-primary me-md-2" >Download PDF</button>
        <button class="btn btn-primary me-md-2" >Download Word</button>

      </form>
    </div>
  )
}

How should I fix this?

Share Improve this question asked Jan 31, 2022 at 2:52 Jaydeep MengwalJaydeep Mengwal 311 gold badge1 silver badge7 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

React hook form does not provide file validation out of the box. However, you can implement a filetype validation yourself.

Try to add something like this to your submit method:

const file = data.selectedfile[0];
if (file.type != "application/pdf") {
    setError("selectedfile", {
        type: "filetype",
        message: "Only PDFs are valid."
    });
    return;
}

I took parts of your code and created an example in this codesandbox.

Read the docs for more information on the setError function.

And if you want more sophisticated client-side validation (for files and in general) you can take a look at this video.

The required property specifies that the input field is required.

This means that the user must select a file to upload. The validate function is used to validate the file that has been uploaded. The function checks to make sure that the file is a PDF file. If it is not, an error message will be displayed.

Here is the working example:

<input
    type="file"
    name="attachment"
    accept="application/pdf"
    ref={register({
        required: true,
        validate: (value) => {
            const acceptedFormats = ['pdf'];
            const fileExtension = value[0]?.name.split('.').pop().toLowerCase();
            if (!acceptedFormats.includes(fileExtension)) {
                return 'Invalid file format. Only PDF files are allowed.';
            }
            return true;
        }
    })}
/>

Maybe it will be a lot easier to just add accept attribute for input?

<label for="poster">Choose a poster:</label>

<input type="file" name="poster" accept="image/png, image/jpeg" 
https://developer.mozilla/en-US/docs/Web/HTML/Attributes/accept

Try this:

<input
    type="file"
    {...register("fileName",{
        required: "Pdf file is Required", // for making the input required
        validate: {

            // If you want other file format, then add them to the array
            fileType:file => ["pdf"].includes(file[0].type.split("/")[1].toLowerCase()) || "The file type should be PDF",

            //Add other validation if you want. For example, checking for file size
            //fileSize:file =>  file[0].size/(1024*1024)<5 || "The file size should be less than 5MB"

        }
    })} 
/>
发布评论

评论列表(0)

  1. 暂无评论