mirror of
https://github.com/n08i40k/schedule-parser-next.git
synced 2025-12-06 09:47:46 +03:00
2.0.0
Я пока перечислю - умру. Надо научиться писать changelog постепенно.
This commit is contained in:
39
src/utility/class-validators/conditional-field.ts
Normal file
39
src/utility/class-validators/conditional-field.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import {
|
||||
registerDecorator,
|
||||
ValidationArguments,
|
||||
ValidationOptions,
|
||||
} from "class-validator";
|
||||
|
||||
// noinspection FunctionNamingConventionJS
|
||||
export function NullIf(
|
||||
canBeNull: (cls: object) => boolean,
|
||||
validationOptions?: ValidationOptions,
|
||||
) {
|
||||
return function (object: object, propertyName: string) {
|
||||
registerDecorator({
|
||||
name: "nullIf",
|
||||
target: object.constructor,
|
||||
propertyName: propertyName,
|
||||
options: validationOptions,
|
||||
constraints: [canBeNull],
|
||||
validator: {
|
||||
validate(value: any, args: ValidationArguments) {
|
||||
const canBeNullFunc: (cls: object) => boolean =
|
||||
args.constraints[0];
|
||||
|
||||
const canBeNull = canBeNullFunc(args.object);
|
||||
const currentValue = value;
|
||||
|
||||
// Логика валидации: если одно из полей null, то другое тоже должно быть null
|
||||
|
||||
return canBeNull
|
||||
? currentValue !== null
|
||||
: currentValue === null;
|
||||
},
|
||||
defaultMessage(args: ValidationArguments) {
|
||||
return `${args.property} must be ${args.property === null ? "non-null" : "null"}!`;
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user