代码之家  ›  专栏  ›  技术社区  ›  Kawd

如何将用户输入格式化为正确的本地化格式?

  •  0
  • Kawd  · 技术社区  · 6 年前

    我有一个 <input type="text"/> 用户可以(尝试)以任何格式/语法键入日期(即使格式无效)。

    我正试着跟着 these guidelines in order to use a local moment

    // I want to use a local instance of moment
    let localLocale = moment();
    
    // I want to set the locale to be 'fr'
    localLocale.locale('fr')
    
    // I want to set the format to be 'LL'
    localLocale.format('LL')
    
    // this is what the user typed in
    let userInput = '2/3/1986'
    
    // I want to do:
    let formattedUserInput = something(userInput)
    

    formattedUserInput 必须是 Mars 2, 1986

    我在找什么 something 应该是。当文档如此混乱的时候,没有解释如何做到这一点。

    如果 userInput 这显然是胡言乱语 something()

    我试过了 localLocale(userInput) 但是它抛出了一个错误 localLocale is not a function

    2 回复  |  直到 6 年前
        1
  •  1
  •   VincenzoC    6 年前

    你可以用 moment(String, String[]) 要分析difefrent格式的输入:

    如果您不知道输入字符串的确切格式,但知道它可能是多种格式之一,则可以使用一组格式。

    你可以用 moment.ISO_8601 ,如图所示 here ,将ISO 8601输入解析为 moment(String)

    请注意 力矩(字符串,字符串[])

    2.3.0 ,矩使用一些简单的启发式方法来确定使用哪种格式。整齐:

    • 更喜欢导致 valid 日期超过无效日期。
    • 更喜欢解析更多字符串而不是更少,使用更多格式而不是更少格式的格式,即更喜欢更严格的解析。
    • 更喜欢数组中较早的格式,而不是较晚的格式。

    一种可能的解决方案如下:

    function something(userInput){
      let m = moment(userInput, [moment.ISO_8601, 'DD/MM/YYYY', 'MM/DD/YYYY' ]);
      if( !m.isValid() ){
        // throw "Invalid input";
      }
      return m.locale('fr').format('LL');
    }
    
    ['2/3/1986', 'aaa', '10-15-2017'].forEach((userInput) => {
      console.log( something(userInput) );
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/locale/fr.js"></script>
        2
  •  -1
  •   Heretic Monkey goproxy.dev    6 年前

    区域设置集是您定义的实例的本地设置。所以

    let localLocale = moment();
    localLocale.locale('fr');
    

    localLocale 'fr'

    // this is what the user typed in
    let userInput = '2/3/1986';
    
    // Use a local instance of moment, using the user's input
    let localLocale = moment(userInput, 'D/M/YYYY');
    
    // Set the locale to be 'fr'
    localLocale.locale('fr');
    
    // Get the formatted string
    let formattedUserInput = localLocale.format('LL');
    
    console.log(formattedUserInput);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment-with-locales.min.js" integrity="sha256-VrmtNHAdGzjNsUNtWYG55xxE9xDTz4gF63x/prKXKH0=" crossorigin="anonymous"></script>