Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
ui-component-library / src / forms / deps / isValidExpiryDate.ts
Size: Mime:
import { isString, toNumber } from 'exotic'

// should stare
const currentDate = new Date()
const currentMonth = currentDate.getMonth() + 1
const currentYear = String(currentDate.getFullYear())
const currentYearTwoDigit = String(currentDate.getFullYear()).slice(2, 4)
const isValidMonth = month => month >= currentMonth && month <= 12
const isValidYear = (year, month) => {
  let validYear = false
  if (year >= currentYear) {
    validYear = !!(
      (year > currentYear && month > 0 && month <= 12) ||
      (year === currentYear && isValidMonth(month))
    )
  } else {
    const expiryYearLength = year.length
    if (expiryYearLength >= 4) {
      validYear = false && isValidMonth(month)
    } else if (expiryYearLength === 2) {
      validYear = !!(
        (year > currentYearTwoDigit && month > 0 && month <= 12) ||
        (year === currentYearTwoDigit && isValidMonth(month))
      )
    }
  }
  return validYear
}

interface FormattedDateObj {
  date: string
  month: number
  year: number
  formattedMonth: string
  formattedYear: string
}

// Date |
type StringyDate = string

const toFormatted = (_date: StringyDate): FormattedDateObj => {
  // 01/10 => 01/2010
  const date = _date.length === 5 ? _date.replace('/', '20') : _date

  const formattedDate = date.replace(/[^0-9]/g, '')

  const formattedMonth = formattedDate
    .replace(/^([2-9])|00/, '0$1')
    .slice(0, 2)
    .replace(/^([1][3-9])/, '1')

  const formattedYear = formattedDate
    .slice(2, 4)
    .replace(/^([0|4-9]\d+|[0|4-9])/, '')

  const obj = {
    date: formattedDate,
    formattedMonth,
    formattedYear,
    month: toNumber(formattedMonth),
    year: toNumber(formattedYear),
  }

  return obj
}

function isValidExpiryDate(date: StringyDate): boolean {
  if (isString(date) === false) {
    return false
  }

  const { formattedYear, formattedMonth, year, month } = toFormatted(date)

  // 01/123 (invalid)
  // 01123 (valid - but edger)
  // 01/12 (valid - correct)
  const isInvalidAmount = date.includes('/') && date.length === 6

  const isWithinMonthRange = month > 0 && month <= 12

  if (!isWithinMonthRange || isInvalidAmount) {
    console.warn('isWithinMonthRange')
    return false
  }
  if (formattedYear.length > 0) {
    const result = isValidYear(year, month)
    return result
  } else {
    return false
  }
}

export { isValidExpiryDate, isValidYear, currentYear, currentYearTwoDigit }
export default isValidExpiryDate