All files / validator/yupSource date.js

46.43% Statements 13/28
29.17% Branches 7/24
55.56% Functions 5/9
46.15% Lines 12/26

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82              3x   4x         2x 1x       1x   1x 1x 2x   2x   2x         3x   4x                                                                                              
import Ref from './Reference'
import { date as locale } from './locale'
import MixedSchema from './mixed'
import inherits from './util/inherits'
import isAbsent from './util/isAbsent'
import isoParse from './util/isodate'
 
let invalidDate = new Date('')
 
let isDate = obj => Object.prototype.toString.call(obj) === '[object Date]'
 
export default DateSchema
 
function DateSchema(payload) {
  if (!(this instanceof DateSchema))
    return typeof payload === 'function'
      ? payload(new DateSchema())
      : new DateSchema()
 
  MixedSchema.call(this, { type: 'date' })
 
  this.withMutation(() => {
    this.transform(function (value) {
      Iif (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
    })
  })
}
 
inherits(DateSchema, MixedSchema, {
  _typeCheck(v) {
    return isDate(v) && !isNaN(v.getTime())
  },
 
  min(min, message = locale.min) {
    var limit = min
 
    if (!Ref.isRef(limit)) {
      limit = this.cast(min)
      if (!this._typeCheck(limit))
        throw new TypeError(
          '`min` must be a Date or a value that can be `cast()` to a Date',
        )
    }
 
    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 = max
 
    if (!Ref.isRef(limit)) {
      limit = this.cast(max)
      if (!this._typeCheck(limit))
        throw new TypeError(
          '`max` must be a Date or a value that can be `cast()` to a Date',
        )
    }
 
    return this.test({
      message,
      name: 'max',
      exclusive: true,
      params: { max },
      test(value) {
        return isAbsent(value) || value <= this.resolve(limit)
      },
    })
  },
})