Ensure that at least one mandatory field is implemented with React final form

Here is a code snippet that handles field validation:

export const isOneFieldValid = (val: string) => { 
  console.log(val)
  return val ? undefined : true
}

...
const validate = (field: string) => {
  switch (field) {
    case 'email': {
      return composeValidators(isOneFieldValid, isValidEmail, hasStringeMaxLength)
    }
    case 'workPhone':
    case 'homePhone':
    case 'mobile': {
      return composeValidators(isOneFieldValid, isNumber, hasNumberMaxLength)
    }
    default:
      return undefined
  }
}
...

I'm wondering if it's possible to validate only a single empty field instead of validating all four fields.

As long as there is at least one way to contact the user, I can proceed with form submission.

Answer №1

It seems like implementing form-level validation instead of field level may be the solution you need.

<Form
    onSubmit={onSubmit}
    validate={values => {
            const errors = {}
            if (values.email && isValidEmail && hasStringMaxLength) {
              return ;
            } else {
             errors.email = 'This field is required';
            }
            if (writeFunctionToCheckWorkPhone) {
              return;
            } else {
              error.workPhone = 'This field is required';
            }
            if (writeFunctionToCheckHomePhone) {
              return ;
            } else {
              error.homePhone = 'This field is required';
            }
           if (writeFunctionToCheckMobile) {
              return ;
            } else {
              error.mobile = 'This field is required';
            }
            return errors;
          }}
    ...

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

(discovered: [object Promise]) utilizing Material UI and DexieJS

Exploring DexieJS and Material UI for the first time has been quite a learning experience, so I may have overlooked a crucial aspect. Here is a glimpse of my code: Subscreen.tsx const [fightersArray, setFightersArray] = useState<FighterEntity[]>([]) ...

Replacing data in a Node server

I am currently working on a server that temporarily stores files in its memory before uploading them to the database. Below is the code snippet I'm using: uploadImage(file, uid, res) { var fs = require('fs'); mongoose.connect(config ...

When running `npx create-react-app my-app`, an error message appears stating: "Typically, you are connected through a proxy which may cause

Encountering an issue while attempting to run npx create-react-app my-app. As a newcomer in the world of node and react, I am eager to create my very first react app. Thankfully, my internet connection seems to be working well. I have made 6 attempts at r ...

Personalized KeyCloak registration link

I need to add a custom request parameter to the registration URL of Keycloak and then extract it into a form. My Approach: Using the Keycloack.js adapter, I successfully generated a custom registration URL in my React project like this: const baseRe ...

How can one obtain a distinct identifier retroactively?

One thing that I am working on is changing button images upon clicking, but this isn't the main issue at hand. Each button corresponds to unique information retrieved from the database, and when clicked, the button should change and send the appropria ...

A guide on dynamically adjusting text size based on viewport width and height in React with TailwindCSS

Utilizing React and Tailwind, I am working towards creating two overlapping rectangles with text. The top rectangle's text should be aligned to the left, while the bottom rectangle's text should be aligned to the right. Regardless of window size ...

Is it recommended to create model classes in React components?

Within the realms of React, the Flux architecture is utilized. According to https://reactjs.org/docs/thinking-in-react.html, React operates with two distinct models - namely, the state and props. There are recommendations provided for model management in ...

Dynamic properties in JQuery

Here is the HTML DOM element I have... <input type="text" style="width: 200px;" id="input1"/> I want to make sure it stores date values. How can I specify that in the DOM element? Please provide your suggestions. Thanks! ...

How can we stop the constant fluctuation of the last number on a number input field with a maxLength restriction

In my ReactJS code, I have an input field that looks like this: <input type="number" onKeyPress={handleKeyPress} maxLength={3} min="0" max="999" step=".1" onPaste={handlePaste} /> Below are the functions associated w ...

A guide to storing data externally by utilizing the useReducer() function

While working on an application with a complex data model, I found that useReducer() is a suitable choice. Instead of sharing my original code, I will be referring to the example from React docs and explaining the modifications I intend to make. Consider ...

Sharing references in React Native using TypeScript: The (property) React.MutableRefObject<null>.current is potentially null

I'm working on a React Native form with multiple fields, and I want the focus to move from one field to the next when the user validates the input using the virtual keyboard. This is what I have so far: <NamedTextInput name={&apo ...

Tips for successfully passing multiple properties to a function in React

<DeleteForeverIcon className={classes.deleteHwIcon} onClick={() => { deleteHomework(value.name, value.class); }} /> I'm looking to modify the function deleteHomework so that it can receive two properties instead of just one. In add ...

What causes the error "Failed to load SWC binary for win32/x64" when using getStaticProps?

Encountering an issue while using getStaticProps() in a Next.js application, resulting in the following error when running the app: warn - Attempted to load @next/swc-win32-x64-gnu, but it was not installed warn - Attempted to load @next/swc-win32-x64-ms ...

Ways to execute a function when a button is clicked with a shared variable?

When creating buttons in HTML to control video speed, I encountered a strange issue. After successfully implementing the buttons for one video, they only worked on a second video and had no impact on the first one. Deleting the second video seemed to resol ...

Preventing ReactJS tooltips from exceeding the boundaries of the screen

Here is a simple demo showcasing blocks with tooltips that appear when hovered over. However, there seems to be an issue with the functionality. The tooltip should ideally be displayed either from the left or right side of the block. To determine the size ...

Dividing CSV Data into Two File Outputs

I've got a CSV file that's structured like this: Docushare Host locale, created_at, version en,Wed Feb 21 17:25:36 UTC 2018,07.00.00.C1.609 User handle, client_data, docCountQuota User-12,,-2 Document handle,client_data,cfSpecialWords Document ...

Transitioning from a fixed position to absolute in CSS3

Sticky Logo Element In my project, I implemented a logo element that is positioned absolutely within the document. As the user scrolls, the logo sticks to the top of the window with a fixed position (you can view an example here: https://jsfiddle.net/swzb ...

Exploring client-server relationships within the Express framework

Is there a way to transfer an object to JavaScript on the client side? I previously asked this question and received an answer, but because I was unable to check it on my computer, I accepted the response. You can view the details here: Client receive jso ...

The AXIOS method in Express.js is designed to return a Promise object that may contain an

I am currently learning ExpressJS and Axios I have created a folder named utils and placed the axios.js file const axios = require('axios'); loadDataPesan=async function(opts){ axios.get('localhost/getData', { params ...

Combine strings in PHP with an alert box in JavaScript

Is there a way to concatenate a string in a JavaScript alert box? I want the first part of the alert box to be a simple text, while the second part is a string retrieved from a MySQL table. $myname = $row["name"]; echo ' <scri ...