@sprucelabs/schema
Version:
Static and dynamic binding plus runtime validation and transformation to ensure your app is sound. 🤓
54 lines (53 loc) • 1.67 kB
JavaScript
import getStartOfDay from '../utilities/getStartOfDay.js';
import isUndefinedOrNull from '../utilities/isUndefinedOrNull.js';
import AbstractField from './AbstractField.js';
class DateField extends AbstractField {
static generateTemplateDetails(options) {
const { definition, importAs, language } = options;
const { isArray } = definition;
const arrayNotation = isArray ? '[]' : '';
return {
valueType: language === 'go'
? `${arrayNotation}${importAs}.DateFieldValue`
: `${importAs}.DateFieldValue${arrayNotation}`,
};
}
validate(value, options) {
const errors = super.validate(value, options);
if (errors.length > 0) {
return errors;
}
return validateDateValue({
value,
isRequired: this.isRequired,
name: this.name,
});
}
toValueType(value) {
return value ? getStartOfDay(+value) : value;
}
}
DateField.description = 'Date and time support.';
export default DateField;
export function validateDateValue(options) {
const { value, isRequired, name } = options;
if (isUndefinedOrNull(value) && !isRequired) {
return [];
}
if (typeof value === 'number' || value instanceof Date) {
return [];
}
else if (typeof value === 'string') {
const date = new Date(value);
if (date.toString() !== 'Invalid Date') {
return [];
}
}
return [
{
name,
code: 'INVALID_PARAMETER',
friendlyMessage: `This doesn't look like a date to me!`,
},
];
}