Skip to content

Commit

Permalink
Allow Date objects for 'date', 'time', and 'date-time' formats.
Browse files Browse the repository at this point in the history
  • Loading branch information
dschnelldavis committed Nov 16, 2017
1 parent 3cbfd67 commit eb34aa0
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 7 deletions.
4 changes: 3 additions & 1 deletion src/lib/src/shared/format-regex.constants.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// AJV fast format regular expressions from:
// updated from AJV fast format regular expressions:
// https://github.com/epoberezkin/ajv/blob/master/lib/compile/formats.js

export const jsonSchemaFormatTests = {
Expand All @@ -7,6 +7,8 @@ export const jsonSchemaFormatTests = {

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

// Modified to allow incomplete entries, such as
// "2000-03-14T01:59:26.535" (needs "Z") or "2000-03-14T01:59" (needs ":00Z")
'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,

// email (sources from jsen validator):
Expand Down
14 changes: 8 additions & 6 deletions src/lib/src/shared/json.validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,19 +331,21 @@ export class JsonValidators {
return (control: AbstractControl, invert = false): ValidationErrors|null => {
if (isEmpty(control.value)) { return null; }
let isValid: boolean;
let currentValue: string = control.value;
if (!isString(currentValue)) {
isValid = false;
} else {
let currentValue: string|Date = control.value;
if (isString(currentValue)) {
const formatTest: Function|RegExp = jsonSchemaFormatTests[requiredFormat];
if (typeof formatTest === 'object') {
isValid = (<RegExp>formatTest).test(currentValue);
isValid = (<RegExp>formatTest).test(<string>currentValue);
} else if (typeof formatTest === 'function') {
isValid = (<Function>formatTest)(currentValue);
isValid = (<Function>formatTest)(<string>currentValue);
} else {
console.error(`format validator error: "${requiredFormat}" is not a recognized format.`);
isValid = true;
}
} else {
// Allow JavaScript Date objects
isValid = ['date', 'time', 'date-time'].includes(requiredFormat) &&
Object.prototype.toString.call(currentValue) === '[object Date]';
}
return xor(isValid, invert) ?
null : { 'format': { requiredFormat, currentValue } };
Expand Down

0 comments on commit eb34aa0

Please sign in to comment.