Yup one of two required email("That doesn't look like a valid I couldn't find any similar case in the docs. min(startTime, "End must be after Start") . Fields that depend on each other need to sorted so they are "constructed" in the right order, e. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company This scenario is very similar to mutually exclusive parameters. You signed out in another tab or window. started must be a valid date. I have a profile creation form in my project for which i am using react-hooks-form and yup library for validation. Like, if carType is "SUV" maximum "noOfPassengers" should be 6 else 4. required('Title is required') But with a change for my case (checking to see if the string is less than or equal to 30) I get an Object is possibly undefined error, even though I believe th ? should be covering the undefined case The closest thing to schema extension/inheritance in Yup is to use object. I need this logic to toggle I'm new to using Yup validation. If one of the fields holds a particular value I would like to remove a different field, along with the associated validation. shape({ countrySelector: Yup. typeError('boo'), This is because yup casts the input object before running validation which will produce: { id: '1', names: { first: undefined }} During the validation phase names exists, and is validated, finding names. when('fieldTwoName', { is: (fieldTwo) => !fieldTwo || fieldTwo. moreThan() to perform this validation logic. string()) . If you want to do this, you need to implement own schema with mixed. nullable(). The first (driver) is required, so it's easy to do it with yup. In . This doesn't work. boolean(). s Please try this schema. Stack Overflow. 0, it seems the property to use is now the optional boolean on SchemaDescription. here is my form structure { flow: [ { text: "hello" }, { input: "world" }, { Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company I have the following schema: const baseSchema = { name: Yup. shape({loginId: yup . nullable()`"} – user13780186 @jquense using that allows for the value to be null - which is not an empty array. ') Yup validate either one of two fields is required (one of them is an array of numbers) 19. I validate this: nome: Yup. So I am looking to merge validationSchema and optionalValidationSchema This is needed because the first variable is the required validations i. literal to at least write the code more declaratively:. 839 15 15 silver badges 33 33 bronze badges. shape to create a new schema based on existing schema: Yup documentation object. I have two fields. ended must not be null and must be a valid date if the started has a valid date value. I wanna make sure at least one of the 2 fields will contain some value. g. string Let's say I have 3 fields: showDiscount, discountType and discountValue. those fields will always needed to be validated whereas optionalValidationSchema will be valid for only certain number of users. required()). In your code, username depends on field phone to validate, but phone depends on usename to validate. 44. shape({ externallyPrintedLabelsQty: yup . () and . nullable() } javascript; formik Yup validate either one of two fields is required (one of them is an array of numbers) 1. required(). Connect and share knowledge within a single location that is structured and easy to search. Type extensions should go in an "ambient" type definition file such as your globals. Year renovated can be left blank, however if there is a value it should be larger than year built (for a renovation certainly must occur after the date it was built). Commented Jul 25, 2022 at 8:54. Reload to refresh your session. It has about 50 fields to be filled and I would like to avoid filling whole object with correct values just to test this one condition. Consider everday common feature of login form with fields username and. Hi I am trying to find a way to compare 2 fields and validate only if they are not equal. typeError('add your message here') it works for me when cast from value NaN is comming. I successfully validated one of the fields with when, but when I tried a cøÿ EUí‡h¤,œ¿ßŸ¦YŸO ½Â:êŽ ´§†uN'•4«;?‡ ØÐ ^M²eþ÷Ù Bc£è¢p}ýJ³{. Web Coding example for the question Yup validate either one of two fields is required one of them is an array of numbers-Reactjs. While the above code works and it solves my problem, i would like to Required, but never shown Post Your Answer generic enum parsing in yup 1. oneOf([yup. object (). In yup you can check depending on other values using when as you did with field4 and field5. Michael Lorton Michael Lorton. If none it's filled, that's also valid. length === const yup = require (' yup ') const {setLocale} = yup setLocale ({mixed: {notType: ' the ${path} is obligatory ', required: ' the field ${path} is obligatory ', oneOf: ' the field ${path} must have one of the following values: When using YUP schemas, and I require two fields. When one of them is filled, the other one is also required. Depending on the yup schema definition, I would like to draw the form components. From what I can see the description seems to have only one representation of the object in the array even if there are multiple instances and in some instances the field might be required and in some not. typeError("End is required") : Yup. If "null" is intended as an empty value be sure to mark the schema as `. Describe the bug I have a usecase where both of these are valid to me { colors: "red"} as well as {colors: ["red", "blue"]} How can I implement something like one of 2 schemas . test('test-compare a few values', 'U suck at math (this is the failure message for the test)', function (value) { // beware, don't use arrow function here otherwise you would not the reference to `this` object let value1 = this Hi I want to write a conditional schema in yup. One answer is object {text: string, is_correct: boolean}. if depend on field A in field B, yup needs to cast and coerce the value in field A before it's groups: yup . How can I make it so only one of the field is required? So if field1 has value, field2 should not be required And if field2 has Yup creates validation schemas for inputs. nullable() . test('len', 'Title must be exactly 5 characters', val => val?. test you will have access for both the values (enteredDate and expirationDate). string(), }). If user enter termination_date, then reason_for_termination must be required. I still want to validate my form with yup, so I tried to use name: yup. The form includes address inputs. I have a problem requiring the account_id field when mode_of_payment has a value. shape({ FirstName: Yup. 2. typeError("Number of Dead simple Object schema validation. The array intervalTime is an ordered time slots with a 15 minutes interval const IntervalT I'm using formik with yup to treat my forms and i need to validate two objects that is setted by formik in initial values: initialValues: { company: { company_name: '', cnpj: '', fantasy_name: '', Const yup require yup const setLocale yup setLocale mixed. required(), ) . yup. There are 6021 other projects in the npm registry using yup. This is the only idea I was able to come up with but it doesn't work: yup . This is a function that returns a Record<keyof T, bool> where T is the generic parameter of the schema, and the boolean is true if the field is marked as required, false otherwise. Using enums as a generic type. You can add DoubleDollarSign = "$$" and so forth to the enum. I want the user to provide either one of the them. I have two integer fields, Year Built & Year Renovated. oneOf([null, 'female', 'male']) . when('phone', { is: (phone) => !phone || phone. of(yup. ) 1 Yup validation with one field but two possible options (OR) Load 7 more related questions Show fewer related questions Sorted by: Reset to default Know someone who can answer? import * as Yup from "yup"; import {commonSchema} from ". I want either one is fill up the data, another one must be required. Yup validate either one of two fields is required (one of them is an array of numbers) 12. And one of them is required How can i do the validation import { useForm, Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. shape ({areas: Yup. 592 10 10 silver At least one of them should be selected: This is how you'll do that logic using yup validation rules; const validationSchema = yup. /common"; export const parentSchema = Yup. This is my current schema let loginSchema = yup. object() . required negates the effects of calling optional() and nullable() Watch out! string(). Ex: I have a required enum that has two values: "ValueA" and "ValueB" The form currently has 3 fields (for arguments sake, let's assume 3 strings which are validated as required fields using Yup). It appears that if you give component and click a type other then any an object with both at least I have a form with react-hooks-form and am trying to use yup validation. shape({ phone1: yup . I achieve the desired behavior using Yup. Following their documentation, I'm using nullable() and optional() but it is still getting validated:. Learn more about Teams Required, but never shown Post Your Answer Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company I'm using yup with formik for validations. shape({ phoneOrEmail: Yup. Define two type fragment or as many as you are required as per your requirement to make the combination of fields required or optional then use the type of query parameter as union like below explanation. In the form there is one field named Github-Username which is optional. required Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company price: Yup. I have two fields itemlist and itemlistUpload I am using react-hook-forms. string() . – Julfikar Haidar. ref('fieldname') is an object, not a single value). – Scott McAllister Similar to this Yup issue: jquense/yup#176 and creating a new issue out of #61. Conditionally making a number field required with YUP in React with react-hook-form. Here is the schema code: const Schema = yup. parent['sibling_form_field_id'] inside the test function to retrieve the values of the other form fields by id. Typed enum instance in TypeScript. object({ existingMortgage: yup. min(Yup. Follow answered Jan 19, 2022 at 1:24. as u can see below I want to make this digital object required only if hasDigital is true other wise keep it optional, I tried below approach but it always says digital. below is my code snippet : Validations code : const signUpSchema = Yup. What you would actually need to do, is to create one entry for title and then have all validation logic as the value:. objec Another approach would be to make use of . Thank you! const schema = yup. I'm trying to achieve making fields required based on condition. How to validate each character in firstName with yup? 1. oneOfValidators( [Yup. I'm building a form in React using Formik and React-bootstrap and I'm using Yup to validate the form. . My need is out of 2 array elements (vehicles), I just need to ensure that at least one is filled with data i. Provide details and share your research! But avoid . object({ name: Yup. Latest version: 1. I am using Formik and Yup for valdiation. That can get clunky at a certain point if there's a giant range of values you'd accept. Remember to actually extend the yup type in your application I have a form with dynamical fields (answers). export const updateAddressSchema = yup. test({ name: 'max', exclusive: false, params: { }, message: '${path} must be less than 10% of the price', test: function (value) { // You can access the price I'm using react-hook-form with yup for my form validation and want some fields to be optional (null). You can use it like: const validationSchema = yup. Related. required("Please enter Phone 1"), phone2: yup . e. 1. I have the following requirements for validation of two fields started and ended. I'm using Formik and Yup for validations. first missing. shape({ file: Yup. required(), value: Yup. min(0, `Minimum tip is $0`) . d. Start using yup in your project by running `npm i yup`. @lvdang I mentioned in the other issue you can use the react-widgets Selectlist and map your checkbox to an array. required("required"), I am using formik for required field. Now, I did not understand if title and author have to be required all the time, for every contentType. matches(/[abcdefghijklmnopqrstuvwxyz]+/ , 'Is not in correct format') . In yup, it is necessary to arrange dependency fields in a specific order of construction. ref('allowOther'), "arrayNumbers are required"), Yup validate either one of two fields is required (one of them is an array of numbers) 5 Dead simple Object schema validation. In one of my form, I want to validate that one <input type="file" /> has a file. I'm using formik for form management in reactjs, i have a question on validation with yup. union with z. Follow edited Jul 21 at 3:08. of (Yup. When showDiscount is set to true and discountType is 'PERCENTAGE', discountValue should be required and should be from 1 to This worked fine with only 2 fields fieldA and fieldB, where each one only had the other field passed in when( but since introducing a third field, I now have a cyclic dependency. referenceMonth !== `${new Here is how you can compare two fields in Yup. Nidhi Dadiya Nidhi Dadiya. But, it's not validating this case, ne This is validation for one input required but i need 2 of 3 – Jan Bo. Schema. I've tested this (and it's not working): Yup. min(1) But you can use this format too: groups: yup . What is the type of enum object. You switched accounts on another tab or window. string(). js to validate some form fields. My code below still doesn't make the account_id required when mode_of_payment has However, I'm a little stuck on arrays with objects where one field is required depending on another field in the same object. max(50, `Имя не может состоять более чем из 50 сомволов`) . But I'm trying to validate that only 1 is selected, using yup - that is the question here. Hot Network Questions PSE Advent Calendar 2024 (Day 21): Wrap-Up Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company import { object, string, array } from 'yup' const schema = object({ emails: array() //how do you validate each email in the array as an actual email? I'm using Yup to validate my form. email(). date() ); but that is just clean up. test() method of Yup JS which allows custom validation but I am not sure how I can write it in this situation. label('Name { array: ["1", "4"] } but I want to add a yup validation to it -- if the array is empty - so at least one item is in the array. It will not allow you to do so, because rest of two field become required. allowOther: Yup. What is the type of an enum in Typescript? 0. required('Please enter the Current Location. const schema = yup. mixed() . UGX. string(), field2: yup. Recently I was working with yup for form validation and I faced the following problem: I have two fields inside my form. ref('allowOther'), 'Must be greater or equal than 0'). ref("area_from"), `AreaTo should be bigger than AreaFrom` ), The problem is I also use custom number formatting in this fields, that returns string, so the field type should be not number but string. literal(15)]), }); This approach also has the added benefit of parsing the exact type 5 | 10 | 15 as the result rather than simply number. I currently have the following Yup validation schema with react-hook-form: const schema = yup. '¹† ùÈÏÏŸu•³ÍŒ€>5Ê%¹åé’-o týÿûYå—@(R XŽ ¹Â-Û O|ˆ€ZH* I§D%CIUÎÙJgî ÿý (¦4W×@‘ @´ë Àè¿€ªdË•=nÛõz7 ¡Úîž E ‚¦¦nÖ*nnǹé«Ö zÒߌ ¹P€Û óyòo”0 É’ mÉîÕ õ ¶Þ Ñ– ûýyÐw(: áÂlð;?O¯Óé÷£ÏïÒ®P šŽ Ö I have the following object: { array: [1] } And the following code: myArray: Yup. To check if the values of two fields are same or not using Yup, you can do: field1: Yup. My object o is big. Do I need a completely different approach, ie. max(255, Mark the schema as required, which will not allow undefined or null as a value. 47. io I'm using Yup to validate my Formik form, but I have no idea how to validate a radio input in Yup/Formik. If user enter Yup validate either one of two fields is required (one of them is an array of numbers) 1. I have several fields that are required if a single condition is true. ValidationToolkit (also here, unfortunately this is only alpha, but you probably could also just extract the method(s) you need from this code and integrate it on your own), it contains the nice sounding attribute RequiredIf which seems to match exactly your cause: You're passing an object to the . Here is my YUP schema for the relevant inputs: I am trying to implement login functionality using Formik and Yup. shape({ field1: yup. Setting: An existing React project, with a signup form. openapi: 3. object({ address: yup . required(), }); If its the other field user need to add the text to the input field: Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Posting my solution in hopes that this helps someone else. shape function and having the title key in there twice results in the first definition being overwritten. of( Yup. required(), }; So I have below validation using Yup : const myValidtion = yup . So you can do this: YUP. 402 There’s always someone who knows more than you. Junior Marques Junior Marques. But there’s always someone who knows less than you, too. notOneOf([undefined]) that should be the sam Yup validation - one field required but not both at the same time 05 March 2020 . array(). Fill telephone field, than fill mobile field, Now erase one of them, You have erased one and one field is still filled. const schema = yup. Required is not working for image. hasVrnts (variant should be required when hasVrnt===1). shape({ subfield: string(). I want to validate a non-required field with yup. I need to make validation schema that at least one I tried to console the errors, but it only display room: { message: "room must be a `array` type, but the final value was: `null` (cast from the value `""`). const schema = z. trim() . object(). shape({ field: yup. Is it possible to have a string OR object condition? So if it is a yup. In rest of two one is filled, one is not filled, so form will not submit. min(1) Share. boolean(), arrayNumbers: Yup. min(2, `Имя не может состоять менее чем из 2 сомволов`) . test('len', 'Must be exactly 5 characters', val => val. literal(10), z. ref('title'), "checkbox is required"), Share. Here test is a non-required field but when user enters we are blocking him to enter some special characters. But for the others 2 fields (fiscalNote & reqNumber) at least one of them should be requi Condition Validation Yup- Any one field is required (Error: Uncaught Error: Cyclic dependency, the node was: "b". Otherwise how you model the schema is up to you, you can use a bunch of boolean fields, an array of values, whatever. Something like this: const phoneOrEmailValidationSchema = Yup. I have two fields, ones is a select control to select the country, and the other one is a Recently I was working with yup for form validation and I faced the following problem: I have two fields inside my form. ie if field x holds the value 'somestring', I would like field y to appear and be required Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company I am creating a form library using React + Material UI + react-hook-form + yup. Based on the validation schema, how can I determine if a particular field is required? (I'm creating a custom text field component, and I Describe the problem I met a problem and i read doc then i using when for process it but not working and throw for me Cyclic dependency issue My schema. I want the user to provide one of them but not both at the same time. parent. shape({ title: Yup. string(), exampleRequired: yup. I would like to submit form if there is only one row (rendered from the beginning) and it is empty and not be able to submit if:. It would really be great if we could easily define this for validation - passing empty arrays as arguments is a very common use case, as we can use them by default with . Given a form with a countries and provinces list I have the follow rule: Country field/select is required Some countries have provinces. Share. ref() and . required("Please enter Phone 2"), phone3: yup . string() What (if possible) is the correct way to define that either the email or phone is a string > 1? var formModelSchema = yup. required Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company yup. object({ currentLocation: yup . test('len', 'Title must be less than 300 characters', val I'm using Yup validation in a React Typescript application. notRequired(): Schema Alias: optional() Mark the schema as not required. ended can be null, means it is not required. The "at least one of" constraint can be represented using minProperties or anyOf. I have 3 fields in my schema. number(). test("dateTest", "Select right month", function (value) { return this. when ('description', {is: desc => Boolean (desc), then: Yup. I am using Formik and yup for its validation. You could replace your when with test like so. Currently, you are checking if both fields are true, in order to check either of the fields is true, you need to override is property to function returning boolean value: title: Yup. Here is a example. shape({ 'fieldOneName': Yup. object({ email: yup. array (). Stack Overflow . I have this validation schema and the field "listType" can have 3 values [0, 1, 2]. Yup conditional validation based on a I want to set validation for number attribute in Yup array of objects, such that weight of each object must be >=0 and <=100 in array. I want to make 3 different conditions for each value of listType and put different validations based on the value I have a form where if a certain radio option is selected I want to render a number input box, which should be required if the radio option is selected. You're almost there but just need some additional info in order to compare two fields. an external validation function or You can use TypeScript's interface merging behavior to extend the schema types if needed. shape({ assets: yup. Follow answered Aug 7, 2020 at 9:52. required("at least one item needs to be here") are empty arrays always truthy? Yup: Validating Array of Strings That Can Be Empty Posted by u/Zealousideal_Water_6 - 8 votes and 4 comments Out of the box I think this is still not possible. One of the parameters of my component is a yup schema to validate the form values. ts. I've tried using a logical OR (||) operator, but it doesn't seem to be working. date() . started must be a past date. 1 - jsDocs. . required(Men but it resolves. min(5, "Address must be more than 5 characters long") . shape(fields: object, noSortEdges?: Array<[string, string]>): Schema I have this schema that validates 2 password fields based on several requirements : "Password must have 8 or more characters, at least one uppercase letter, and one number. There are 5700 other projects in the npm registry using yup. The problem I am facing is: say I have three fields fieldA, fieldB and fieldC. shape() I believe its call the noSortEdges value. Actually I have a watcher that sets at the start an array of objects: [ { "code": "english", I have two select inputs pickUpTime and dropOffTime in react-hook-form populated with an array of strings. Alternatively, you could use Yup. But I found this promising article about Mvc. unique('contractNum', 'Please provide a unique number. This allows you to keep the required directive on the subfield whether or not the parent schema/field containing it is empty at validation time. const Schema = Yup. number. max(20) Documentation for npm package yup@1. Yup validate either one of two fields is required (one of them is an array In yup 1. Web yup validation at least one field required. From your proposed schema, I suppose they should be required all the time. string()]) . 0. I have a JSON object which contains an array of JSON objects. Learn more about it here. you must cast and coerce the value in field phone before passing it to field username, or vice versa In your case, your schema must be something like: I found this a bit complicated to explain and haven't found any solutions out there. " "Password Since your validation for openingDate is pretty stright forward as in the schema for openingDate won't change (as per my understanding), i would suggest you to make use of test rather than when. Enum in TypeScript. And you can actually listen to more than one field at the same time. I have initialized the initial values: const initialValues = Hello! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. union([z. 6. pages is required , even when I'm passing hasDigital false. both can't be empty. But try to submit. max(255). I need to check if field contains phone number OR email. length === 5). Improve this answer. mixed() but now I get obviously problems with the min. Basically, you can use an object-type parameter where parameter_1 and parameter_2 are the object properties; such object will be serialized as ?parameter_1=value1¶meter_2=value2. tips: number() . Yup. You can use yup. required(), }). FieldA is not required but FieldB is required if . required(Yup. – Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company title: Yup. You have to be careful with cyclic dependencies. 2. ref() in your case. In general, when using validationSchema, it is best practices to ensure that all of your form's fields have initial values so that Yup can see them immediately. What you use completely depends on what type of I have 2 dropdowns in each row and I can dynamically add and remove rows apart form the first one. test. min(2) . object({ example: yup. min(1). optional() . It works fine for now, but I am trying to make the field 'variant' required depending on the value of product[0]. oneOf([0 , 1], 'Selecting the gender field is required'), }); Share. I use yup for form validation. '), hometown: I'm validating a field by using YUP as validator, but I already made an test in it, and i'm having trouble to add another validation. required("Please enter Phone 3"), }); I belive I have to use . Hi, Yes, you can handle in RAML by defining Types fragment . object({ prop: z. myArray: yup. There is some solution using the param noSortEdges but there is not much documentation around it. Here is the answer from SO that might help with that. At the moment, the sha I want to validate one field on the basis of other using my schema. Can the logic be applied to what you need? – Ryan Zeelie. required() . array( yup. 3. image: yup. test( "At least one of these fields needs to be filled", (value) Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company Thanks for an extremely informative and well formed response. I tried by removing required tag from hasDigital but Here is a minimal failing example which happens to use formik but actually I am doing server side validation using yup. – I wanna validate fields with yup and react-hook-form. When the user select a country, the API will fetch a list of Sometimes when you are validating large and nested objects with yup and you wanna do a validation based (conditional validation) on a Yeah this is a bit of a gotcha. literal(5), z. That can get slightly tedious to write out so it might make sense if you I'm creating an form with three fields. Sum of weights of all objects in array also must be les I am trying to validate using yup. Remember that you are answering the question for readers in the future, not just the person asking now. Something like the following should achieve what you require: let I have a form field (shapes) that should be required when at least one of two other fields (colors & sizes) next to it are filled out. The other three fields A B C are required only if one of the other two fields is filled in. Create a Yup validation object, and wire it up to a form – easy. The result would look like: <Formik initialValues={{ email: '', showEmail: false }} How to use Yup validation to make the field mandatory if 1 of the other 3 fields are not empty? I tried the following schema but got cyclic dependency issue. 3k 26 26 gold badges 107 107 Above code snippet is to add a unique method in yup. Asking for help, clarification, or responding to other answers. Please make a note I have used moment. This is working for every field in form, but with image it's not working. 4. I’ve played a little bit with different ideas to get solution below. NOTE: Formik author here To make Yup. Validate array with 2 Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company In this particular case you could use z. when the user didn't enter anything then also it is validating( i don't need this validation until user enters something). I am using formik for form validation and came across some problems in array validation. I've tried something like this - but its not working. Scenario: i have 4 fields and i want to validate using Yup validation schema Suppose if the user enters value for any of the above 1 field, the other 3 must be required if the user does not enter I have following yup validator. shape ({name: Yup. map and other array operations even when empty. const validationSchema = Yup. 5. Follow answered Sep 27, 2022 at 13:23. boolean() . Skip to main content. trim (). I have 2 fields, let's say FieldA and FieldB. test() to perform whatever sort of validation you want in a function, e. string()), yup. when work properly, you would have to add showEmail to initialValues and to your Yup schema shape. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company I started using Yup with react-hook-form, but I have some problems. required('Title is required'), checkbox: Yup. Type of enum values. How can I make it so only one of the field is required? So if field1 has value, field2 should not be required And if field2 has value, field1 is not required. required('Please select the country'), }); JSX snippet When using YUP schemas, and I require two fields. Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company The first mistake I saw in your code is not using functions for then and otherwise, if you are using the latest version of yup. 2 paths: /foo: Given a React state variable const [selectedFormtype, setSelectedFormtype] = useState<Nullable<MyFormTypeVm>>() Types/interfaces are defined like this type Nullable<T> = T | null Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers; Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand; OverflowAI GenAI features for Teams; OverflowAPI Train & fine-tune LLMs; Labs The future of collective knowledge sharing; About the company The 2 checkboxes are distinct items (and I could add a 3rd checkbox, independent of the other 2) - radio buttons aren't really suitable here. string(), field3: yup. max cannot reference other field and calculate with it at validation. shape({ lang: Yup. This is my validation schema: Here's a less mindbending way to do it than the other answer. shape({ name: Yup. string() then, min/max will be used, otherwise just yup. I've been playing with this example so I can better understand it. What I want to be able to do however, is to do conditional requirement on 1 or 2 fields without making the entire object partial and while having access to all of the fields in the object. 0, last published: 6 months ago. Working example: I am using yup with formik for managing my form. Is there a better way to condense this code to avoid repeating the when for all of these fields? const requiredForDiffAddres area_to: Yup. The issue you are running into is that there is no "default" input for a group of checkboxes. If field1 is false, field2 OR field3 are required. mixed() and description: yup. matches() functions. string() const schema2 = Yup. shape({ gender: Yup. I believe I need to use yup's ref() as well as yup's when() Whats the best way to allow only two specified values in the selector, for example I have 2 fields for a user to select : US. '), newMortgage: yup. But i want You can use this. I was using Yup. length === 0, then: Yup. There is logic in the form to disable checkbox1 when checkbox2 is selected, and vice versa. required) works a little different and additionally prevents empty string values ('') when required. The current default is fine, because you want to cover potential You are write its work. array schema. For some reason the urls and instructions are undefined (see where it's Hey, I have an object that can is by default undefined, and accept one of null or a stringvalue. value1 is selected without value 2 I'm using Yup. Year Built is a required field, Year Renovated is not. min( Yup. ref incorrectly (Yup. If you wish to avoid this behavior do one of the following: Set the nested default to undefined: names. import { ObjectSchema, SchemaDescription } from "yup"; type FormObject = You signed in with another tab or window. I want the user to provide one of them but not both export const mySchema = yup. default(undefined) My questions is what is happening behind the scenes, and what is happening regarding the second argument in Yup. number() . But try this scenario. Justin McCraw. string (). 0, last published: 3 months ago. default(undefined), }); // Or How can I modify my validation schema such that the entered value is boolean, either 1 or 0? not true false etc formValue: Yup. { email: yup . The “country” input was not a Yup is a JavaScript object schema validator and object parser.
uklz qyhjks lotstfr frbtp tdohjbv pcanrd vxad gugag fwchuzz lqxkjej