Skip to content

Commit

Permalink
fix(validation): fix date validation custom decorator
Browse files Browse the repository at this point in the history
  • Loading branch information
ivashog committed Mar 24, 2021
1 parent 1bacc19 commit c5cbc56
Showing 1 changed file with 12 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,23 @@ export class IsValidDateConstraint implements ValidatorConstraintInterface {
const { format, allowFuture, strict, min, max } = this.getConstraintsWithDefaults(
args.constraints,
);
const parsedMomentDate = moment(date, format, strict);
const isValidFormat = parsedMomentDate.isValid();
const parsedDate = moment(date, format, strict);
const now = moment();

if (!isValidFormat) return false;

const parsedDate = parsedMomentDate.toDate();
if (!parsedDate.isValid()) return false;

if (!allowFuture && !min && !max) {
return parsedDate <= new Date();
return parsedDate.isSameOrBefore(now);
} else if (min && max) {
return min <= parsedDate && max >= parsedDate;
} else if (!allowFuture) {
return parsedDate.isBetween(min, max, undefined, '[]');
} else if (!allowFuture && min) {
return parsedDate.isBetween(min, now, undefined, '[]');
} else {
return min
? min <= parsedDate && parsedDate <= new Date()
? parsedDate.isSameOrAfter(min)
: max
? max >= parsedDate && parsedDate <= new Date()
? parsedDate.isSameOrBefore(max)
: true;
} else {
return min ? min <= parsedDate : max ? max >= parsedDate : true;
}
}

Expand All @@ -40,8 +38,8 @@ export class IsValidDateConstraint implements ValidatorConstraintInterface {
return (
`Date '${args.value}' is invalid! ` +
`Allowed formats: '${format}'; allowed interval: ` +
`from '${min ? this.formatDate(min) : 'any'}' ` +
`to '${max ? this.formatDate(max) : this.formatDate()}'`
`from '${min ? this.formatDate(min, format as string) : 'any'}' ` +
`to '${max ? this.formatDate(max, format as string) : this.formatDate()}'`
);
}

Expand Down

0 comments on commit c5cbc56

Please sign in to comment.