all files / src/ length.js

100% Statements 25/25
100% Branches 39/39
100% Functions 3/3
100% Lines 21/21
1 branch Ignored     
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                   28× 28×   28× 28× 28× 28× 28×     28× 27×           20×           15×                  
import React from 'react'
import { FormattedMessage } from 'react-intl'
import { formatMessage, prepare, isNumber, memoize, DEFAULT_ALLOW_BLANK } from './helpers'
 
 
let length = memoize(function ({
      '=': equal, is,
      max, maximum,
      min, minimum,
      'in': range, within,
      message, msg,
      'if': ifCond, unless,
      allowBlank=DEFAULT_ALLOW_BLANK
    }) {
  msg   = formatMessage(msg || message)
 
  equal = isNumber(equal) ? equal : is
  min   = isNumber(min)   ? min   : minimum
  max   = isNumber(max)   ? max   : maximum
  range = range || within
  if (range && isNumber(range[0]) && isNumber(range[1])) {
    min = range[0]
    max = range[1]
  }
 
  return prepare(ifCond, unless, allowBlank, function (value) {
    if (isNumber(equal) && value.length !== +equal) {
      return msg || (
        <FormattedMessage id="form.errors.wrongLength"
          defaultMessage="is the wrong length (should be {count, number} {count, plural, one {character} other {characters}})"
          values={{ count: equal }} />
      )
    }
    if (isNumber(max) && value.length > +max) {
      return msg || (
        <FormattedMessage id="form.errors.tooLong"
          defaultMessage="is too long (maximum is {count, number} {count, plural, one {character} other {characters}})"
          values={{ count: max }} />
      )
    }
    if (isNumber(min) && value.length < +min) {
      return msg || (
        <FormattedMessage id="form.errors.tooShort"
          defaultMessage="is too short (minimum is {count, number} {count, plural, one {character} other {characters}})"
          values={{ count: min }} />
      )
    }
  })
})
 
export default length