Skip to content

Reference

Bv edited this page May 5, 2021 · 1 revision

Nope Reference Documentation

Allows the schema to reference other values in the provided entry

Signature:

Nope.ref(keyOrPath: string)

Example:

const schema = Nope.object().shape({
  email: Nope.string().email().atMost(255).required(),
  confirmEmail: Nope.string().oneOf(
    [Nope.ref("email")],
    "Must match the first email"
  ),
});

const errors = schema.validate({
  email: "me@gmail.com",
  confirmEmail: "you@gmail.com",
});
console.log(errors); // { confirmEmail: 'Must match the first email' }

const noerrors = schema.validate({
  email: "me@gmail.com",
  confirmEmail: "me@gmail.com",
});

console.log(noerrors); // undefined
const schema = Nope.object().shape({
  validUsernames: Nope.array().of(Nope.string()),
  user: Nope.object().shape({
    name: Nope.string().oneOf(Nope.ref("../validUsernames"), "not valid"),
  }),
});

const invalidInput = {
  validUsernames: ["megatron"],
  user: {
    name: "ultron",
  },
};

expect(schema.validate(invalidInput1)).toEqual({
  user: {
    name: "not valid",
  },
});