-
-
Notifications
You must be signed in to change notification settings - Fork 14
Array
- required
- of
- ofAsync
- minLength
- maxLength
- mustContain
- hasOnly
- every
- some
- length
- default
- getDefault
- nullable
- nonNullable
- defined
- optional
- notRequired
- isValid
- isValidSync
- when
- oneOf
- notOneOf
- required
- notAllowed
- test
- validate
Required field (not nil)
Signature:
required<T>(message: string)
Example:
const validator = Nope.array().required("requiredError");
validator.validate(null); // returns requiredError
validator.validate([42]); // returns undefinedRequire the values to be of a certain type
Signature:
of(type: Validatable<T>)
Example:
const schema = Nope.object().shape({
names: Nope.array().of(Nope.string().min(5)).required(),
});
schema.validate({
names: ["Geralt"],
}); // returns undefined;If you are using async schema validation, please use ofAsync instead of the normal of
Validate if array is greater than a certain length
Signature:
minLength(length: number, message?: string)
Example:
const validator = Nope.array().minLength(5, "minLengthErrorMessage");
validator.validate(undefined); // returns undefined
validator.validate([1, 2, 3, 4, 5, 6]); // returns undefined
validator.validate([1, 2, 3, 4]); // returns 'minLengthErrorMessage'Max length of the field
Signature:
maxLength(length: number, message?: string)
Example:
const validator = Nope.array().maxLength(5, "maxLengthErrorMessage");
validator.validate(undefined); // returns undefined
validator.validate([1, 2, 3, 4]); // returns undefined
validator.validate([1, 2, 3, 4, 5, 6]); // returns 'minLengthErrorMessage'Must contain a certain item
Signature:
mustContain(value: T, message?: string)
Example:
const validator = Nope.array().mustContain(2, "containError");
validator.validate([1, 3, 4]); // returns 'containError'
validator.validate([1, 2, 3, 4]); // returns undefinedMust only contain certain items
Signature:
hasOnly(values: T[], message?: string)
Example:
const validator = Nope.array().hasOnly([1, 2, 3], "invalidEntries");
validator.validate([1, 2, 3]); // returns undefined
validator.validate([1, 2, 3, 4]); // returns 'invalidEntries'
validator.validate([4, 5, 6]); // returns 'invalidEntries'const validator = Nope.array()
.of(Nope.array().of(Nope.string()))
.hasOnly([["a"]], "invalidEntries");
validator.validate([["a"]]); // returns undefined
validator.validate([["b"]]); // returns 'invalidEntries'Every item passes predicate. Alike Array.prototype.every
Signature:
every(predicate: item => boolean, message?: string)
Example:
const isEven = (value) => value % 2 === 0;
const validator = Nope.array().every(isEven, "everyError");
validator.validate(undefined); // returns undefined
validator.validate([]); // returns undefined
validator.validate([2, 4, 6]); // returns undefined
validator.validate([1, 2, 4]); // returns 'everyError'
validator.validate([1, 3, 5]); // returns 'everyError'Some items pass the predicate. Alike Array.prorotype.some
Signature:
some(predicate: item => boolean, message?: string)
Example:
const isEven = (value: number) => value % 2 === 0;
const validator = Nope.array<any>().some(isEven, 'whereSomeError');
validator.validate(undefined) // returns undefined
validator.validate([]) // returns undefined
validator.validate([1,2,3]) // returns undefined
validator.validate([2,4,6]) // returns undefined
validator.validate([1,3,5]) // returns 'whereSomeError'Asserts if the array has exactly the given number of items.
Signature:
length(size: number, message?: string)
Example:
Nope.array().length(3).validate(["a", "b", "c"]); // returns undefined
Nope.array().length(3).validate(["a"]); // returns the error messageSet a fallback value used when the input is undefined.
Signature:
default(value: T)
Defaults apply only when the input is undefined. They do not replace null, empty strings, false, 0, or empty arrays.
Example:
const schema = Nope.string().default("Anonymous");
schema.validate(undefined); // returns undefined (uses "Anonymous")
schema.validate(null); // does not use the defaultReturns the value set by default(), or undefined if no default was configured.
Signature:
getDefault(): T | undefined
Example:
Nope.string().default("Anonymous").getDefault(); // "Anonymous"
Nope.string().getDefault(); // undefinedAllows null as a valid value. Does not automatically allow undefined.
Signature:
nullable()
Example:
Nope.string().nullable().validate(null); // returns undefined
Nope.string().nullable().defined().validate(undefined); // returns error messageRejects null. This is the default behavior unless nullable() was called.
Signature:
nonNullable(message?: string)
Example:
Nope.string().nonNullable("no null").validate(null); // returns "no null"Rejects undefined. Does not affect null handling — use nullable() / nonNullable() for that.
Signature:
defined(message?: string)
Example:
Nope.string().defined("must be defined").validate(undefined); // returns "must be defined"
Nope.string().defined().validate("hello"); // returns undefinedAllows undefined. Does not automatically allow or reject null.
Signature:
optional()
Example:
Nope.string().optional().email().validate(undefined); // returns undefined
Nope.string().optional().email().validate("not-an-email"); // returns error messageAlias for optional().
Signature:
notRequired()
Example:
Nope.string().notRequired().validate(undefined); // returns undefinedReturns a Promise<boolean> indicating whether the value passes validation. Does not throw validation errors.
Signature:
isValid(entry?: T, context?: object): Promise<boolean>
Example:
const schema = Nope.string().email();
await schema.isValid("test@example.com"); // true
await schema.isValid("invalid"); // falseSynchronous version of isValid(). Returns a boolean and does not throw validation errors.
Signature:
isValidSync(entry?: T, context?: object): boolean
Example:
const schema = Nope.string().email();
schema.isValidSync("test@example.com"); // true
schema.isValidSync("invalid"); // falseConditional validation of a key
Signature:
when(key: string | string[], conditionObject: { is: boolean | ((...args: any) => boolean), then: NopeSchema, otherwise: NopeSchema })
key - set of keys (or a single key) that the is predicate should run on. Note that you can access the parent object(s) by using the ../ syntax as shown in the 2nd example
conditionObject:
is - a boolean flag (which will run the .every method on the values and assert the against the passed is) or a predicate that will decide what schema will be active at that moment.
then - schema in case is param is truthy
otherwise - schema in case the is param is falsy
Example:
const schema = Nope.object().shape({
check: Nope.boolean().required(),
test: Nope.string().when("check", {
is: true,
then: Nope.string().atLeast(5, "minError").required(),
otherwise: Nope.string().atMost(5).required(),
}),
});
schema.validate({
check: true,
test: "test",
}); // { test: 'minError' }
// or as a predicate
const schema2 = Nope.object().shape({
check: Nope.boolean(),
check2: Nope.boolean(),
test: Nope.string().when(["check", "check2"], {
is: (check, check2) => check && check2,
then: Nope.string().atLeast(5, "minError").required(),
otherwise: Nope.string().atMost(5).required(),
}),
});
schema.validate({
check: true,
check2: false,
test: "testing",
}); // { test: 'maxError' }const schema = Nope.object().shape({
shouldCreateUser: Nope.boolean().required("reqbool"),
user: Nope.object().shape({
name: Nope.string().when("../shouldCreateUser", {
is: (str) => !!str,
then: Nope.string().required("required"),
otherwise: Nope.string().notAllowed("not allowed"),
}),
}),
});
const validInput1 = {
shouldCreateUser: true,
user: {
name: "user name",
},
};
const invalidInput1 = {
shouldCreateUser: true,
user: {
name: undefined,
},
};
expect(schema.validate(validInput1)).toEqual(undefined);
expect(schema.validate(invalidInput1)).toEqual({
user: {
name: "required",
},
});Asserts if the entry is one of the defined options
Signature:
oneOf(options: string | ref[], message: string)
Example
Nope.string().oneOf(["a", "b", "c"]).validate("b"); // returns undefined
Nope.string().oneOf(["a", "b", "c"]).validate("d"); // returns the error messageAsserts if the entry is none of the defined options
Signature:
notOneOf(options: number | ref[], message: string)
Example:
Nope.string().notOneOf([1, 2, 3]).validate(5); // returns undefined
Nope.string().notOneOf([1, 2, 3]).validate(2); // returns the error messageAsserts if the entry is not nil (undefined or null)
Signature:
required(message: string)
Example:
Nope.string().required().validate("b"); // returns undefined
Nope.string().required().validate(); // returns the error messageAsserts if the entry is nil
Signature:
notAllowed(message: string)
Example:
Nope.string().notAllowed().validate(null); // returns undefined
Nope.string().notAllowed().validate("42"); // returns the error messageAdd a custom rule
Signature:
test(rule: (entry: T) => string | undefined)
Example:
Nope.string()
.test((a) => (a === "42" ? undefined : "Must be 42"))
.validate("42"); // returns undefined
Nope.string()
.test((a) => (a === "42" ? undefined : "Must be 42"))
.validate("41"); // returns the error messageRuns the rule chain against an entry
Signature:
validate(entry: string | undefined | null)
Can be seen in use in the examples above