Is there a way to validate time using Moment JS?

前端 未结 2 1543
囚心锁ツ
囚心锁ツ 2021-02-19 06:24

Is there a way to validate if the String passed as time is valid using Moment JS?

The operations moment(\"2014-12-13 asdasd\",\"YYYY-MM-DD LT\").isValid() o

2条回答
  •  有刺的猬
    2021-02-19 06:43

    As described in the documentation, as of moment 2.3.0, you can pass a third parameter true which turns on "strict parsing" mode.

    moment("2014-12-13 asdasd","YYYY-MM-DD LT", true).isValid()   // false
    
    moment("2014-12-13 12:34 PM","YYYY-MM-DD LT", true).isValid()   // true
    

    The down side is that it must match the locale's format (i.e. the one supplied as the second argument) exactly. Since LT is equivalent to h:mm A in English, it will only accept 12-hour time without seconds. If you pass 24 hour time, or pass seconds, then it will fail.

    moment("2014-12-13 12:34:00 PM","YYYY-MM-DD LT", true).isValid()   // false
    moment("2014-12-13 15:00","YYYY-MM-DD LT", true).isValid()         // false
    

    A better solution might be to pass multiple formats with strict parsing:

    var formats = ["YYYY-MM-DD LT","YYYY-MM-DD h:mm:ss A","YYYY-MM-DD HH:mm:ss","YYYY-MM-DD HH:mm"];
    moment("2014-12-13 12:34 PM", formats, true).isValid()     // true
    moment("2014-12-13 15:00", formats, true).isValid()        // true
    moment("2014-12-13 12:34:00 PM", formats, true).isValid()  // true
    

提交回复
热议问题