Implementing type-based validations in Vue.js 3 using Yup

Greetings! I am facing a minor issue that needs to be addressed. The scenario is as follows: I need to implement validation based on the type of member. If the member type is corporate, then the tax number should be mandatory while the phone number can be left empty. Conversely, if the member type is individual, the opposite rules should apply.

For clarification: When the value is false, only phone validations are required. However, when the value is true, only tax validations are necessary.

setup() {
const value = ref(false);
const validationSchema = Yup.object().shape({
  phone: Yup.string().trim().required().label("Phone"),
  tax: Yup.string().trim().required().label("Tax"),
});

const { handleSubmit } = useForm({ validationSchema });
const submit = handleSubmit(async (values) => {
  console.log("personName:", values);
});
return {
  validationSchema,
  submit,
  value,
};

},

https://i.stack.imgur.com/GbNCi.png

https://i.stack.imgur.com/ZRbnO.png

Answer №1

Include the memberType in the validation process with the following approach:

const validationSchema = Yup.object().shape({
  memberType: Yup.string().required(),
  phone: Yup
    .string()
    .trim()
    .label("Phone")
    .when("memberType", {
        is: "individual",
        then: Yup.string().required("Please provide a phone number")
     }),
  tax: Yup
    .string()
    .trim()
    .label("Tax")
    .when("memberType", {
        is: "corporate",
        then: Yup.string().required("Please enter tax identification number")
     }),
});

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

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...

State in Vuex can be modified by invoking the store actions

Currently, I have implemented two functions in my store. One function retrieves data by making API calls, while the other function toggles changes on the "approved" cell. Everything seems to be functioning correctly, except for the fact that after toggling ...

Setting up a Contact Email for your Nuxt Static Generated site: A Step-by-Step Guide

I have a website built on Nuxt and hosted on Netlify. I utilized the 'static' method in my nuxt.config.js file to generate the dist folder. My goal is to trigger an email notification whenever a user submits a contact form on my site. It functio ...

Error encountered while building with Next.js using TypeScript: SyntaxError - Unexpected token 'export' in data export

For access to the code, click here => https://codesandbox.io/s/sweet-mcclintock-dhczx?file=/pages/index.js The initial issue arises when attempting to use @iconify-icons/cryptocurrency with next.js and typescript (specifically in typescript). SyntaxErr ...

Struggling to synchronize animation timing between elements using jquery

When you navigate to an album (for example, Nature because I'm still working on the others) and select one of the images, they all gradually fade out while the selected image appears on the screen. What's actually happening is that the selected i ...

What is the best way to extract a number from a string in JavaScript?

There are instances in HTML files where a <p> tag displays the price of a product, such as ""1,200,000 Dollar"". When a user adds this product to their cart, I want the webpage to show the total price in the cart. In JavaScript, I aim to e ...

NodeJS - Issue: The procedure specified could not be located in the bcrypt_lib.node

After upgrading from Node.js 0.12.7 to 4.2.1, I encountered an error when attempting to start my server: $ node server.js C:\Users\me\documents\github\angular-express-auth\node_modules\bcrypt\node_modules\bindi ...

Retrieving JSON information from a PHP script with AJAX

I am currently experiencing an issue with my PHP script, 'getNews.php'. Despite working correctly in the terminal and returning the expected data, I am encountering difficulties when trying to retrieve this information through JavaScript. <?p ...

Encountering difficulties setting cookies within the app router in Next.js

I've been diving into next.js and I'm trying to figure out how to set a cookie using the code below. However, I'm encountering an error: "Unhandled Runtime Error. Error: Cookies can only be modified in a Server Action or Route Handler." I ...

Setting the 'redirect_uri' for Identity Server 4 in a React JS application and directing it to a specific view using a route

After following the instructions at , I attempted to login to Identity Server from my ReactJS application. Upon successful login, http://localhost:3000/callback.html was loaded with id_token and access_token in the URL. However, I noticed that this callbac ...

Locate the element within the specified parameters using [protractor]

Here's my query: element.all(by.repeater('user in users')).then(function(rows) { // looking to locate an element in rows using CSS selector, for example } UPDATE : I want to clarify that I am trying to find an element using rows[rows.len ...

Implementing child components in React using TypeScript and passing them as props

Is it possible to append content to a parent component in React by passing it through props? For example: function MyComponent(props: IMyProps) { return ( {<props.parent>}{myStuff}{</props.parent>} } Would it be feasible to use the new compone ...

The bootstrap switch button remains in a neutral grey color

Ordinary: Initially clicked: Click again: After the second click, it remains grey and only reverts on a different action like mouse click or selection. Is there a way to make it go back to its original state when unselected? ...

The Issue of Anti Forgery Token Not Functioning Properly with Ajax JSON.stringify Post

I have been attempting to utilize an Anti Forgery token with JSON.stringify, but despite researching multiple sources, I have not been successful. Below is my AJAX code for deleting some information without any issues. Upon adding the anti forgery token, I ...

Updating the scope variable in an AngularJS directive

Recently delving into Angular, I encountered an issue: I have both a list view and a details view with tags. To facilitate navigating between the two views and loading new elements from a service upon click events, I created a directive. My aim is to also ...

How to extract just the year from Material-UI's date picker in React

const displayYearOnly = (date) => { const year = date.getFullYear(); console.log(year); }; return ( <div style={{ marginRight: "20px" }}> <LocalizationProvider dateAdapter={AdapterDayjs}> <DemoContainer componen ...

Exploring the depths of time travel in Redux without the aid of developer

Has anyone successfully achieved time traveling capabilities with Redux core? It seems that this feature is limited to the devtools and not advised for production use. I had planned on implementing Redux in a multiplayer game to assist with managing clie ...

Is there an effective way to merge two collections?

I came across an issue where I am attempting to merge two arrays that resemble the ones listed below: var participants = [ {id: 1, name: "abe"}, {id:2, name:"joe"} ]; var results = [ ...

A step-by-step guide on how to verify a selection using JavaScript

Is it possible to validate the select option with JavaScript? For example, if a user selects "Admin," then the page works for admin login. If they select "Vendor," then it works for vendor login. <table class="login_table" width="100%" border="0" cells ...

Invalid Syntax: The token '21' is found unexpectedly at column 12 in the expression [2013-08-28 21:10:14] beginning at [21:10:14]

I'm in the process of creating a straightforward directive for a date countdown. However, I've hit a roadblock with this particular error: Syntax Error: Token '21' is an unexpected token at column 12 of the expression [2013-08-28 21:10 ...