33 lines
1.2 KiB
TypeScript
33 lines
1.2 KiB
TypeScript
import {
|
|
ValidationArguments,
|
|
ValidatorConstraint,
|
|
ValidatorConstraintInterface,
|
|
} from 'class-validator';
|
|
import { I18nContext } from 'nestjs-i18n';
|
|
|
|
@ValidatorConstraint({ name: 'MatchFields', async: false })
|
|
export class MatchFieldsConstraint implements ValidatorConstraintInterface {
|
|
validate(value: any, args: ValidationArguments): boolean {
|
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
const [property] = args.constraints;
|
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
|
|
const relatedValue = (args.object as any)[property];
|
|
|
|
return value === relatedValue;
|
|
}
|
|
|
|
defaultMessage(args: ValidationArguments): string {
|
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
|
|
const [property] = args.constraints;
|
|
const i18n = I18nContext.current();
|
|
|
|
const field1 = i18n?.t(`users.fields.${args.property}`) ?? args.property;
|
|
const field2 = i18n?.t(`users.fields.${property}`) ?? (property as string);
|
|
|
|
return (
|
|
i18n?.t('validation.fieldsMustMatch', { args: { field1, field2 } }) ??
|
|
`${args.property} must match ${property}`
|
|
);
|
|
}
|
|
}
|