Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ensure that array only contains set values from a variable. #1465

Closed
DavidIlie opened this issue Sep 16, 2021 · 2 comments
Closed

Ensure that array only contains set values from a variable. #1465

DavidIlie opened this issue Sep 16, 2021 · 2 comments

Comments

@DavidIlie
Copy link

Hey everyone,

I have been working on a project where a person is supposed to select a couple of radio buttons which their value gets put in an array.

Screenshot 2021-09-16 100124

That works perfectly however I want to validate the final array to make sure that there aren't any invalid values in the array.
I already have an array with all the correct values but I don't know how to make yup check if the array doesn't contain strings that don't match the pre-defined array.

[
  'image:view', 'image:upload',
  'image:list', 'image:delete',
  'file:view',  'file:upload',
  'file:list',  'file:delete',
  'text:view',  'text:upload',
  'text:list',  'text:delete'
]

This is my yup schema:

export const createAPIKeySchema = yup.object().shape({
    name: yup
        .string()
        .min(4, "Name can't be less than 4 characters.")
        .max(32, "Name can't be more than 32 characters.")
        .required(),
    permissions: yup
        .array()
        .of(yup.string())
        .defined()
        .required()
        .min(1, "You must pick at least one option."),
});

Any help would be appreciated, thanks!

@DavidIlie
Copy link
Author

This is what I did to get it working:

import * as yup from "yup";

import { isPermission } from "../api-tokens/index";

export const createAPIKeySchema = yup.object().shape({
    name: yup
        .string()
        .min(4, "Name can't be less than 4 characters.")
        .max(32, "Name can't be more than 32 characters.")
        .required(),
    permissions: yup
        .array()
        .of(
            yup
                .string()
                .test("valid", "This is not a valid permission!", (val) => {
                    if (isPermission(val)) return true;
                    return false;
                })
        )
        .defined()
        .required()
        .min(1, "You must pick at least one option."),
});

@dbernar1
Copy link

Alternative:

yup
.array()
.of(
  yup
    .string()
    .oneOf([
      "monday",
      "tuesday",
      "wednesday",
      "thursday",
      "friday",
      "saturday",
      "sunday",
    ])
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants