【问题标题】:How to validate a input-field with JavaScript no matter which date format it is?无论是哪种日期格式,如何使用 JavaScript 验证输入字段?
【发布时间】:2018-07-26 07:31:24
【问题描述】:

我有一个输入字段。语言环境参数在开头定义(如'ch-de')。我想根据 locale 参数验证输入。 例如,当区域设置为'en-uk' 时,日期必须为7/25/2018,但当区域设置为'de-ch' 时,日期必须为25.7.2018

此外,应该可以为每种格式编写7/5/201807/05/201807/5/20187/05/2018

我该如何解决这个问题?

【问题讨论】:

标签: javascript html validation ecmascript-6


【解决方案1】:

我做了这个解决方案:

export const isDateValid = (locale = 'en-uk', inputValue = '') => {
  const date = new Date(inputValue);
  let objDate = '';
  const numeric = 'numeric';
  const twoDigit = '2-digit';
  const selectors = [numeric, twoDigit];
  const filters = ['year', 'month', 'day'];
  let options = {};
  let valid = false;

  filters.forEach((filter) => {
    options[filter] = '';
  });

  const combinations = [];
  selectors.forEach((el1) => {
    selectors.forEach((el2) => {
      options = ({
        year: selectors[0],
        month: el1,
        day: el2,
      });
      combinations.push(options);
    });
  });

  combinations.forEach((option) => {
    objDate = date.toLocaleString(locale, option);
    console.log(objDate, inputValue);
    if (objDate === inputValue && date.getFullYear().toString().length === 4) {
      console.log('richtig!!!!!');
      valid = true;
    }
  });
  return valid;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    • 1970-01-01
    • 2018-06-11
    • 1970-01-01
    • 1970-01-01
    • 2011-11-07
    • 1970-01-01
    相关资源
    最近更新 更多