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

The preflight request's response failed to meet the access control criteria due to the absence of the 'Access-Control-Allow-Origin' header

I encountered an issue while using ngResource to call a REST API hosted on Amazon Web Services: Upon making the request to , I received the following error message: "XMLHttpRequest cannot load. Response to preflight request doesn't pass access cont ...

What could be causing the React.js axios data to display on the console but not on the screen?

I am currently working on a React Axios Project using data from . The characters data includes another API link, so I implemented an Axios loop to display the names of the characters. While I can see the characters' names in the console, they are not ...

Provide JSON data from the index method to the index.html file located in the public directory

I'm currently working on building a single page application using Rails as the backend, since it's the only framework I am familiar with. All my project files are stored in the public folder, and I've also set up npm and jspm to incorporate ...

The AJAX validation process fails to run prior to the execution of the login PHP script

My attempt to implement AJAX for form validation is not successful and I'm unsure why. Despite my efforts, the form still redirects to login_action.php instead of performing the AJAX validation as intended. I have designed a modal login form and wish ...

Need help resolving validation errors in vee-validate?

Is there a way to remove all the errors generated by vee-validate when signing out? The following code does not seem to work, as the form errors are still displaying. Why is that? sign_out: function (e) { console.log('sign me out') var s ...

At times, the loading image fails to appear on Ajax

Take a look at my code below: function apply_image_effect(){ $.ajax({ url: "image/image.php", global: false, type: "POST", data: ({my_color:encodeURIComponent($('#my_color').val()),my_size:$('#my_size&apos ...

What causes an error in a basic Vue2 <script setup> example?

I previously developed Vue2 components using the class-based style and am now looking to transition my codebase to utilize the composition API. According to the documentation, the composition API and the script setup method for writing single file componen ...

Disassociate all globally linked modules in npm network

If I want to display a list of all npm modules linked globally using npm link ..., I can execute the following command: npm ls -g --depth=0 --link=true But is there a way to remove or unlink all of these linked modules at once? With over 10 dependencies, ...

I can't seem to understand why the error "bash: ng: command not found" keeps popping up even though I

Ever since I installed Angular CLI and started working with Angular, something strange happened - the ng command suddenly became not found: ng serve -o Here's a screenshot for reference: bash: ng: command not found Oddly enough, when I use the npx c ...

Mastering the ng-submit directive for AngularJS

Having an issue with my form that submits a location to Google's Geocoder and updates the map with the lat/long. When using ng-click on the icon, it requires double clicking to work properly. And when using ng-submit on the form, it appends to the URL ...

Tips for shifting a designated row upward in Chrome using JavaScript

Currently, I am working on a Javascript function that moves up a selected row. However, the issue I am facing is that when the row moves up, the old row is not being removed. For instance, if I move up the 'bbbb' row, it successfully moves up bu ...

Utilizing HTML to call a function and fetching data from AngularJS

I've been struggling to retrieve the value after calling a function in my HTML file. Despite trying various methods after conducting research, I have not achieved success yet. Take a look at the code below: HTML: <div class="form-group"> & ...

Is it obligatory to reply with status code 200 in Express?

Is it required to explicitly include a status 200 code in the response or is it set automatically? response.json({ status: 'OK', }); vs. response .status(200) .json({ status: 'OK', }); Upon testing the route in my browser, ...

The Ajax response fails to update my viewmodel

I have a value and a list that I need to update from within an Ajax callback. After retrieving a fresh value using .get(), I try to assign it to my view model's property, but the UI does not refresh properly. Below is the code snippet: function Searc ...

Concealing a div depending on the price variation

I'm looking for a way to dynamically show or hide a div based on the price of selected variations in my online store. Let's take a product with options priced at £359 and £455 as an example. In addition, there is a finance plugin with a minim ...

Error in Java script due to the combination of Jmeter and Selenium APIs

While using Jmeter in conjunction with Selenium WebDriver, I encountered an unhandled error "016/02/17 16:51:47 ERROR - com.googlecode.jmeter.plugins.webdriver.sampler.WebDriverSampler: :14:94 Expected , but found ; WDS.browser.findElement(pkg.By.cssSele ...

An option instead of using a pop-up window

Currently, I have a PHP script and a small form that allows users to upload image files. The user can access this feature by clicking on a button on the parent HTML page, which opens up a Pop Up Window. I understand that not everyone is a fan of 'Pop ...

What is the best way to upload a file and data simultaneously using Axios?

I'm currently facing an issue with posting data in a Vue application. Specifically, I am struggling with incorporating an image file input within the form. While most resources suggest sending the file separately or alongside other files,[1][2] What ...

Ensure that the date range picker consistently shows dates in a sequential order

Currently utilizing the vuetify date range picker component https://i.stack.imgur.com/s5s19.png At this moment, it is showcasing https://i.stack.imgur.com/GgTgP.png I am looking to enforce a specific display format, always showing the lesser date first ...

Exploring the Possibilities of Utilizing Async Middleware for Error Handling in VueJS Router

Greetings, this is my inaugural question on Stack Overflow. For my Frontend, I am utilizing VueJS and for Backend, Laravel. My current predicament involves loading a model from the backend API that requires user editing. However, there are policies in pla ...