All files / lib/validations/validate/card date.js

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 83 84 85 86 87 88 89 90 91 92                                              2x   2x 7x   7x           2x 10x   2x 6x   2x 4x   2x 7x   2x         2x 5x   5x           2x 7x 7x   7x   7x             2x 13x         13x                        
import {
  F,
  T,
  add,
  and,
  both,
  cond,
  equals,
  gt,
  ifElse,
  length,
  lt,
  lte,
  merge,
  modulo,
  pipe,
  prop,
  replace,
  splitEvery,
  toString,
  zipObj,
} from 'ramda'
 
const clean = replace(/[^0-9]/g, '')
 
const getCurrentDate = () => {
  const date = new Date()
 
  return {
    currentYear: modulo(date.getFullYear(), 1000),
    currentMonth: add(date.getMonth(), 1),
  }
}
 
const cardDateLessThanCurrentDate = (props, dates) =>
  lt(prop(props[0], dates), prop(props[1], dates))
 
const isInvalidYear = dates =>
  cardDateLessThanCurrentDate(['year', 'currentYear'], dates)
 
const monthLessThanCurrentMonth = dates =>
  cardDateLessThanCurrentDate(['month', 'currentMonth'], dates)
 
const yearEqualsCurrentYear = dates =>
  equals(prop('year', dates), prop('currentYear', dates))
 
const isExpiredDate = both(
  yearEqualsCurrentYear,
  monthLessThanCurrentMonth
)
 
const isValidMonth = (dates) => {
  const month = prop('month', dates)
 
  return and(
    lte(month, 12),
    gt(month, 0)
  )
}
 
const validateDate = (date) => {
  const dateArray = splitEvery(2, date).map(Number)
  const dateObj = zipObj(['month', 'year'], dateArray)
 
  const dates = merge(dateObj, getCurrentDate())
 
  return cond([
    [isExpiredDate, F],
    [isInvalidYear, F],
    [T, isValidMonth],
  ])(dates)
}
 
const validate = (date) => {
  const lengthIsFour = pipe(
    length,
    equals(4)
  )
 
  return ifElse(
    lengthIsFour,
    validateDate,
    F
  )(date)
}
 
export default pipe(
  toString,
  clean,
  validate
)