0

How do I create a function where a key of an object is dynamically set from the function

export const validateObjectId = (key: string = 'id'): ObjectSchema => {
  return Joi.object({
    key: Joi.string()
      .regex(/^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i)
      .required(),
  });
};

how do I make the key be the key of the object

1
  • I don't understand, you're validating the key property on the object?
    – Celsiuss
    Jul 16, 2020 at 23:02

2 Answers 2

1

I've been able to find a way out using the code snippet below

export const validateObjectId = (key: string = 'id'): ObjectSchema => {
  interface Obj {
    [key: string]: Object;
  }

  const object: Obj = {};

  object[key] = Joi.string()
    .regex(/^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i)
    .required();
  return Joi.object(object);
};
1

Maybe you can try the following:

export const validateObjectId = (key: string = 'id'): ObjectSchema => {
    let object: any = {};
    object[key] = Joi.string()
          .regex(/^(?=[a-f\d]{24}$)(\d+[a-f]|[a-f]+\d)/i)
          .required();
    return Joi.object(object);
}

Cheers

1
  • I just fixed a syntax error (made object of type any and removed the var before object[key] = ...), it should be typescript-compliant now. Let me know if it still doesn't work (and what the error is if that's the case)
    – tooomg
    Jul 16, 2020 at 23:38

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.