joi icon indicating copy to clipboard operation
joi copied to clipboard

Joi.string().pattern() fails when dealing with different contexts

Open CS-Birb opened this issue 4 years ago • 2 comments

Support plan

  • is this issue currently blocking your project? (yes/no): Not at present
  • is this issue affecting a production system? (yes/no): No

Context

  • node version: v14.15.5
  • module version with issue: v17.4.2
  • last module version without issue: N/A
  • environment (e.g. node, browser, native): Node & Browser
  • used with (e.g. hapi application, another framework, standalone, ...): Universal (SSR) Nuxt Application
  • any other relevant information:

What are you trying to achieve or the steps to reproduce?

Due to different global contexts, .pattern() fails in certain scenarios, I.e. Server-side rendering using Nuxt. However, this could be achieved just as simply using a subwindow with window.open()

I.e.

const a = window.open();
console.log(a.RegExp == RegExp); // false

const b = /123/;
console.log(b instanceof a.RegExp); // false

https://github.com/sideway/joi/blob/63b324497f03d9d39612b404da157e81d9c5aea9/lib/types/string.js#L531 Joi's current assertion is that regex instanceof RegExp, but as seen above this fails in niche (but valid, and not altogether uncommon) usecases. While not as safe, other alternatives could be to assert regex?.constructor.name === "RegExp" or to produce a new regex in the validating context RegExp(regex). Which approach is most desirable is your call, naturally.

What was the result you got?

regex must be a RegExp error.

What result did you expect?

To have a functional validation schema using .regex() across contexts.

CS-Birb avatar Sep 02 '21 23:09 CS-Birb

Further notes about this quirk with instanceof available at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof#instanceof_and_multiple_context_e.g._frames_or_windows

CS-Birb avatar Sep 03 '21 12:09 CS-Birb

The issue still exist

stonega avatar Apr 26 '22 07:04 stonega