@openactive/data-model-validator
Version:
A library to allow a developer to validate a JSON document against the OpenActive Modelling Opportunity Specification
60 lines (57 loc) • 1.81 kB
JavaScript
const moment = require('moment');
const Rule = require('../rule');
const Field = require('../../classes/field');
const ValidationErrorType = require('../../errors/validation-error-type');
const ValidationErrorCategory = require('../../errors/validation-error-category');
const ValidationErrorSeverity = require('../../errors/validation-error-severity');
module.exports = class DateFormatRule extends Rule {
constructor(options) {
super(options);
this.targetFields = '*';
this.meta = {
name: 'DateFormatRule',
description: 'Validates that Date properties are in the correct format.',
tests: {
default: {
message: 'Dates must be expressed as ISO 8601 dates. For example, `"2018-08-01"`.',
category: ValidationErrorCategory.CONFORMANCE,
severity: ValidationErrorSeverity.FAILURE,
type: ValidationErrorType.INVALID_FORMAT,
},
},
};
}
validateField(node, field) {
const errors = [];
let fieldObj;
if (node.model.hasSpecification) {
fieldObj = node.model.getField(field);
if (typeof fieldObj === 'undefined') {
return [];
}
} else {
fieldObj = new Field({}, node.options.version);
}
const fieldValue = node.getValue(field);
const type = fieldObj.detectType(fieldValue);
if (type === 'https://schema.org/Date'
|| fieldObj.isOnlyType('https://schema.org/Date')
) {
if (
!moment(fieldValue, 'YYYY-MM-DD', true).isValid()
&& !moment(fieldValue, 'YYYYMMDD', true).isValid()
) {
errors.push(
this.createError(
'default',
{
value: fieldValue,
path: node.getPath(field),
},
),
);
}
}
return errors;
}
};