Zod handling the visual component

I am currently working on a project using react-file-base64 to handle file metadata such as name, type, size, and base64 encoding. Despite registering zod validation, I encountered an "image required error" even after uploading the image. Upon investigation, it seems that zod is not recognizing any image object for verification. How can I resolve this issue?

interface featured_image_types {
    name: string;
    type: string;
    size: string;
    base64: string
}

 const schema = z.object({
        blog: z.any({ required_error: "Please enter a blog content, it cannot be empty!!!" }),
        title: z.string().min(5, { message: "Title should be atleast minimum 5 characters" }).refine((val) => console.log(val)),
        reading_time: z.string({ required_error: "Reading Time required" }),
        featured_image:  z
        .any()
        // Custom refinement function to log files
        .refine((files) => {
        console.log(files, "this not rertriviing files here");
          // Return null to ensure the validation continues
        return true;
        })
        // To not allow empty files
        .refine((files) => files?.length >= 1, { message: 'Image is required.' })
        // To not allow files other than images
        .refine((files) => ACCEPTED_IMAGE_TYPES.includes(files?.[0]?.type), {
        message: '.jpg, .jpeg, .png and .webp files are accepted.',
        })
        // To not allow files larger than 5MB
        .refine((files) => files?.[0]?.size <= MAX_FILE_SIZE, {
        message: `Max file size is 5MB.`,
        }),
        blog_cat: z.string({ required_error: "Please select one of blog cateogry" }).min(6, { message: "Please select one of blog cateogry" }),
        tags: z.any()
    })
    
<div>
<label className="block mb-2 text-sm font-bold" htmlFor="file_input">Featured Image</label>

 <FileBase
     type = 'file'
     {...register('featured_image')}
     multiple={false}
     onDone={(file: featured_image_types) => setSomething({ ...something, featured_image: file })}
                            />

    {errors.featured_image && <p className="text-red-500">{errors?.featured_image?.message?.toString()}</p>}

                        </div>
                        
// This part returned undefined
.refine((files) => {
        console.log(files, "this not rertriviing files here");
          // Return true to ensure the validation continues
        })

Answer №1

Here are a couple of recommendations to consider:

  • Try testing your schema in a REPL, browser console, or similar tool by parsing different inputs to see how it behaves.

For example:

z.any().refine(it => {console.log(it); return true}).parse('anything')
  • Instead of using multiple refine functions, think about utilizing
    z.array(z.object{name: z.string(), ... })
    . This may result in a cleaner and more readable code.

In this case, the issue might not be with your zod schema. Check if you are passing the correct value to schema.parse and make sure that the featured_image property is included.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to use Lodash to quickly return the same value if a condition is met using the ternary operator

Is there a condensed way to do this using Lodash? (or perhaps Vanilla JS/TypeScript) var val = _.get(obj, 'value', ''); Please note that var val = obj.value || ''; is not suitable as it considers 0 and false as valid but fal ...

Error: Type '() => () => Promise<void>' is not compatible with type 'EffectCallback'

Here is the code that I'm currently working with: useEffect(() => { document.querySelector('body').style['background-color'] = 'rgba(173, 232, 244,0.2)'; window.$crisp.push(['do', 'ch ...

Is it possible for Visual Studio 2013 to compile TypeScript files even without node.js installed?

My current setup involves using TypeScript in combination with Visual Studio Code and the tsc CLI with node.js installed. I recently made an interesting discovery about tsc - I always assumed it was a javascript program, but then I started to wonder how ...

Executing JavaScript functions when a browser tab is closed

When a user closes the browser tab, I want to call a specific JavaScript function. However, I only want this to occur when the user is actually closing the browser, not during page refreshes, link navigation, form submissions, or pressing the back button. ...

Understanding the process of parsing JSON response using JavaScript

I am facing an issue with reading a JSON object in JavaScript. I have received this JSON object as a response and now I need to create a jstree based on it. Here is my JavaScript code: var repoId = $('#frmHdnV').val(); // variable to hold req ...

Assigning ng-Attributes using vanilla JavaScript

My journey with coding Angular started not too long ago. I have a HTML structure with various divs and classes. I am looking to loop through these classes and add a tooltip to a specific div within each class. Rather than hardcoding the Angular attributes ...

JavaScript loop used to create markers on Google Maps

I am currently in the process of developing a basic Google map which includes markers and involves looping through the data source for the markers. When I replace key.lng or key.lat with hardcoded values in the code below, everything functions correctly. ...

Using Highcharts to dynamically color a map based on data values in a React TypeScript project

I'm attempting to generate a map where each country is filled with colors based on its specific data, similar to the example shown in this map. I am looking for a functionality akin to the use of the formatter function within the tooltip. I have expe ...

What is the best way to set a default value for a specified Date format retrieved from an API?

Here are examples of different data formats for ReleaseDate: 2014-09-23 09:00:00.923Z /Date(1407369600210)/ If you want to access this information from an API, you can use the following object dot-notation: result.data.Items[0].ReleaseDate Sometimes, ...

When the return false statement is included, the form fails to submit and instead refreshes on the current page

I recently discussed an issue regarding triggering a dialog box before confirming a submit action. Unfortunately, after implementing this, the document no longer submits when expected. Instead, it just remains on the same page with the same settings. I h ...

Transform the JSON object into a TypeScript array

Currently working on a project that requires converting a JSON object into a TypeScript array. The structure of the JSON is as follows: { "uiMessages" : { "ui.downtime.search.title" : "Search Message", "ui.user.editroles.sodviolation.entries" : ...

Trigger a click event on a nested Angular 13 component to remove a class from its grandparent component

In my Angular 13 project, I am working with 3 components: Child Component : Burger-menu Parent Component : Header Grand-Parent Component : app.component.html Within the burger-menu component, there is a close button. When this button is clicked, I want t ...

Transmitting information to the service array through relentless perseverance

I need assistance finding a solution to my question. Can my friends help me out? What types of requests do I receive: facebook, linkedin, reddit I want to simplify my code and avoid writing lengthy blocks. How can I create a check loop to send the same ...

Is it possible to convert a leaflet marker into a nuxt-link function?

Recently, I started using nuxt and vue-leaflet to create an interactive map, even though I am quite new to it. This map consists of multiple markers representing different locations. The goal is for the respective page to open when a user clicks on a mark ...

Possibly include an example or a step-by-step guide to provide additional value and make the content more

Enhance the main array by adding the second and third arrays as properties http://jsfiddle.net/eRj9V/ var main = [{ 'id': 1, //'second':[ // {'something':'here'}, //{'something':' ...

Google Maps drawing lines are not showing up at all

I am having an issue with displaying polylines while using Javascript generated through the googleVis package for R. I have tested it on different browsers but encountered the same problem. Below is a snippet of R code that generates the error, followed by ...

Encapsulating functions with multiple definitions in Typescript

Struggling with wrapping a function that can have multiple return types based on input parameters in Typescript. Imagine wanting a function to return ReturnA for VariantEnum.a and ReturnB for VariantEnum.b. Consider this implementation of sampleFunction: ...

Steps for creating duplicates of jQuery elements

My Objective I am currently working on a project that involves allowing users to modify an SVG file based on input, such as text formatting (bold, italic, etc.). It is important that the user can revert back to the original template without having to relo ...

TS2339 Error: The property does not exist on this particular type when referencing a file relatively

Currently, I am in the process of developing my own UMD library using typescript and webpack. However, I encountered an issue when importing a file that resulted in the error TS2339 (Property 'makeRequest' does not exist on type 'typeof Util ...

Using three.js for creating particle systems with custom particle geometries

In my three.js project, I am working with a standard system of particles. However, I am curious if it is feasible to use different geometries for the particles, like boxes or planes. I am attempting to create falling bullet particles, but I am facing an is ...