繁体   English   中英

如何在 react-hook-form 中验证输入 type='file'?

[英]How can I validate a input type='file' in react-hook-form?

我正在为我的项目使用反应钩子形式。 我如何验证输入类型='文件'? 它应该只接受 pdf。 当我想要只允许 pdf 时,它现在已成功插入数据库。 我正在使用react hook form v7。如果有人知道请建议我。 提前致谢!

这是我的代码

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>
  )
}

我应该如何解决这个问题?

React 钩子表单不提供开箱即用的文件验证。 但是,您可以自己实现文件类型验证。

尝试将这样的内容添加到您的提交方法中:

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

我获取了您的部分代码并在此代码框中创建了一个示例。

阅读文档以获取有关setError function 的更多信息。

如果您想要更复杂的客户端验证(对于文件和一般情况),您可以观看视频。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM