将日期标准化为DD / MM / YYYY-Redux表格

时间:2018-07-12 08:42:49

标签: reactjs redux redux-form

我正在使用redux表单和日期选择器作为组件,但是用户也可以从键盘输入日期。我想使用redux格式的规范化道具将日期更改为“ MM / DD / YYYY”格式,因此用户只需输入数字,然后添加前两个“ /”,然后再添加两个相同的数字即可。因此,例如,当有人粘贴“ 12122012”时,输入中将包含“ 12/12/2012”值。

1 个答案:

答案 0 :(得分:1)

normalize组件上使用Redux-form的<Field />道具,您可以添加此函数以将日期归一化为mm/dd/YYYY格式。

function normalizeDate(value, prevValue) {
  if (!value) return value;

  const valueOnlyNumbers = value.replace(/[^\d]/g, '');
  const prevValueOnlyNumbers = prevValue && prevValue.replace(/[^\d]/g, '');

  // Enable backspacing:
  // if the user is backspacing and they backspace a forward slash, the date's
  // numbers won't be affected so just return the value.
  if (valueOnlyNumbers === prevValueOnlyNumbers) return value;

  const month = valueOnlyNumbers.slice(0, 2);
  const day = valueOnlyNumbers.slice(2, 4);
  const year = valueOnlyNumbers.slice(4, 8);

  if (valueOnlyNumbers.length < 2) return `${month}`;
  if (valueOnlyNumbers.length == 2) return `${month}/`;
  if (valueOnlyNumbers.length < 4) return `${month}/${day}`;
  if (valueOnlyNumbers.length == 4) return `${month}/${day}/`;
  if (valueOnlyNumbers.length > 4) return `${month}/${day}/${year}`;
}