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? Commented 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);
};
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

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)

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.