Skip to content

Commit eb34aa0

Browse files
committed
Allow Date objects for 'date', 'time', and 'date-time' formats.
1 parent 3cbfd67 commit eb34aa0

File tree

2 files changed

+11
-7
lines changed

2 files changed

+11
-7
lines changed

src/lib/src/shared/format-regex.constants.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// AJV fast format regular expressions from:
1+
// updated from AJV fast format regular expressions:
22
// https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js
33

44
export const jsonSchemaFormatTests = {
@@ -7,6 +7,8 @@ export const jsonSchemaFormatTests = {
77

88
'time': /^[0-2]\d:[0-5]\d:[0-5]\d(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
99

10+
// Modified to allow incomplete entries, such as
11+
// "2000-03-14T01:59:26.535" (needs "Z") or "2000-03-14T01:59" (needs ":00Z")
1012
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s][0-2]\d:[0-5]\d(?::[0-5]\d)?(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
1113

1214
// email (sources from jsen validator):

src/lib/src/shared/json.validators.ts

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -331,19 +331,21 @@ export class JsonValidators {
331331
return (control: AbstractControl, invert = false): ValidationErrors|null => {
332332
if (isEmpty(control.value)) { return null; }
333333
let isValid: boolean;
334-
let currentValue: string = control.value;
335-
if (!isString(currentValue)) {
336-
isValid = false;
337-
} else {
334+
let currentValue: string|Date = control.value;
335+
if (isString(currentValue)) {
338336
const formatTest: Function|RegExp = jsonSchemaFormatTests[requiredFormat];
339337
if (typeof formatTest === 'object') {
340-
isValid = (<RegExp>formatTest).test(currentValue);
338+
isValid = (<RegExp>formatTest).test(<string>currentValue);
341339
} else if (typeof formatTest === 'function') {
342-
isValid = (<Function>formatTest)(currentValue);
340+
isValid = (<Function>formatTest)(<string>currentValue);
343341
} else {
344342
console.error(`format validator error: "${requiredFormat}" is not a recognized format.`);
345343
isValid = true;
346344
}
345+
} else {
346+
// Allow JavaScript Date objects
347+
isValid = ['date', 'time', 'date-time'].includes(requiredFormat) &&
348+
Object.prototype.toString.call(currentValue) === '[object Date]';
347349
}
348350
return xor(isValid, invert) ?
349351
null : { 'format': { requiredFormat, currentValue } };

0 commit comments

Comments
 (0)