84 lines
1.9 KiB
JavaScript
84 lines
1.9 KiB
JavaScript
// @ts-ignore
|
|
import isoParse from './util/isodate';
|
|
import { date as locale } from './locale';
|
|
import isAbsent from './util/isAbsent';
|
|
import Ref from './Reference';
|
|
import BaseSchema from './schema';
|
|
let invalidDate = new Date('');
|
|
|
|
let isDate = obj => Object.prototype.toString.call(obj) === '[object Date]';
|
|
|
|
export function create() {
|
|
return new DateSchema();
|
|
}
|
|
export default class DateSchema extends BaseSchema {
|
|
constructor() {
|
|
super({
|
|
type: 'date'
|
|
});
|
|
this.withMutation(() => {
|
|
this.transform(function (value) {
|
|
if (this.isType(value)) return value;
|
|
value = isoParse(value); // 0 is a valid timestamp equivalent to 1970-01-01T00:00:00Z(unix epoch) or before.
|
|
|
|
return !isNaN(value) ? new Date(value) : invalidDate;
|
|
});
|
|
});
|
|
}
|
|
|
|
_typeCheck(v) {
|
|
return isDate(v) && !isNaN(v.getTime());
|
|
}
|
|
|
|
prepareParam(ref, name) {
|
|
let param;
|
|
|
|
if (!Ref.isRef(ref)) {
|
|
let cast = this.cast(ref);
|
|
if (!this._typeCheck(cast)) throw new TypeError(`\`${name}\` must be a Date or a value that can be \`cast()\` to a Date`);
|
|
param = cast;
|
|
} else {
|
|
param = ref;
|
|
}
|
|
|
|
return param;
|
|
}
|
|
|
|
min(min, message = locale.min) {
|
|
let limit = this.prepareParam(min, 'min');
|
|
return this.test({
|
|
message,
|
|
name: 'min',
|
|
exclusive: true,
|
|
params: {
|
|
min
|
|
},
|
|
|
|
test(value) {
|
|
return isAbsent(value) || value >= this.resolve(limit);
|
|
}
|
|
|
|
});
|
|
}
|
|
|
|
max(max, message = locale.max) {
|
|
var limit = this.prepareParam(max, 'max');
|
|
return this.test({
|
|
message,
|
|
name: 'max',
|
|
exclusive: true,
|
|
params: {
|
|
max
|
|
},
|
|
|
|
test(value) {
|
|
return isAbsent(value) || value <= this.resolve(limit);
|
|
}
|
|
|
|
});
|
|
}
|
|
|
|
}
|
|
DateSchema.INVALID_DATE = invalidDate;
|
|
create.prototype = DateSchema.prototype;
|
|
create.INVALID_DATE = invalidDate; |