question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Require only one of 4 fields

See original GitHub issue
validationSchema={
  Yup.object().shape({
    emailAddress: Yup.string().email('Please enter a valid email address'),
    phoneHome: Yup.number().typeError('Home Phone must be a number'),
    phoneMobile: Yup.number().typeError('Mobile Phone must be a number'),
    phoneWork: Yup.number().typeError('Work Phone must be a number'),
  })
  .test(
    'at-least-one-contact',
    'You must provide at least one contact method',
    value => {
      const test = !!(value.emailAddress || value.phoneHome || value.phoneMobile || value.phoneWork);
      return Yup.ValidationError(['emailAddress', 'phoneHome', 'phoneMobile', 'phoneWork'], 'one is required', '');
    }
  )
}

Basically I am getting an error on the value => { definition saying

Type 'ValidationError' is not assignable to type 'boolean | Promise<boolean>'.

Is there an easy way to do this so only one field is required?

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:9 (2 by maintainers)

github_iconTop GitHub Comments

45reactions
risenforcescommented, May 13, 2019

I use this:

const Yup = require('yup')

Yup.addMethod(Yup.object, 'atLeastOneOf', function(list) {
  return this.test({
    name: 'atLeastOneOf',
    message: '${path} must have at least one of these keys: ${keys}',
    exclusive: true,
    params: { keys: list.join(', ') },
    test: value => value == null || list.some(f => value[f] != null)
  })
})

const Schema = Yup.object()
  .shape({
    one: Yup.number(),
    two: Yup.number(),
    three: Yup.number()
  })
  .atLeastOneOf(['one', 'two'])

Schema.isValidSync({ three: 3 }) // false
Schema.isValidSync({ one: 1, three: 3 }) // true
12reactions
NathanHealeacommented, Aug 20, 2019

@calmattack,

I had a similar situation and solved it with the following code.

My solution requires selecting other input elements and checking the value. With more time you could probable adept @risenforces solution to pass in the schema for validation instead of selecting elements.

yup.addMethod(yup.string, 'requiredIf', function(list, message) {
  return this.test('requiredIf', message, function(value) {
    const { path, createError } = this;

    // check if any in list contain value
    // true : one or more are contains a value
    // false: none contain a value
    var anyHasValue = list.some(value => {

      // return `true` if value is not empty, return `false` if value is empty
      return Boolean(document.querySelector(`input[name="${value}"]`).value);
    
    });

    // returns `CreateError` current value is empty and no value is found, returns `false` if current value is not empty and one other field is not empty.
    return !value && !anyHasValue
      ? createError({ path, message })
      : true;
  });
});


const schema = yup.object().shape({
  email: yup.string().requiredIf(['work','home','cell']),
  work: yup.string().requiredIf(['email','home','cell']),
  home: yup.string().requiredIf(['email','work','cell']),
  cell: yup.string().requiredIf(['email','work','home']),
});
Read more comments on GitHub >

github_iconTop Results From Across the Web

at least one field is required in angular 4 forms - Stack Overflow
I'm using angular 4 forms and I ...
Read more >
Requiring at least one field - FormValidation
Requiring at least one field. In fact, the form might have multiple fields with the same validator rules but at least one of...
Read more >
Restrict data input by using validation rules - Microsoft Support
You can compare values across different fields using a record validation rule. For example, a record with two date fields might require that...
Read more >
TypeScript: Modeling Required Fields with Mapped Types
This is just a another little TypeScript tip I'll spend too long explaining. ... For example there is Partial that makes all fields...
Read more >
Queries and Mutations - GraphQL
Try adding an appearsIn field to the hero object in the query, and see the new result. In the previous example, we just...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found