有没有一种方法可以使用Moment JS验证时间? [英] Is there a way to validate time using Moment JS?

查看:306
本文介绍了有没有一种方法可以使用Moment JS验证时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种方法可以验证使用Moment JS作为时间传递的字符串是否有效?

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

操作moment("2014-12-13 asdasd","YYYY-MM-DD LT").isValid()moment("asdasd","LT").isValid()等同于true,理想情况下不应发生.

The operations moment("2014-12-13 asdasd","YYYY-MM-DD LT").isValid() or moment("asdasd","LT").isValid() equate to true which ideally shouldn't happen.

我的应用程序使用多种语言,对于我来说,真的不可能提出RegEx模式来验证字符串.例如,如果我将时间字符串设为"午前12時12分0秒",则Moment JS应该能够对此进行验证.我检查了源,发现库中的时间检查不是那么严格.我可能错过了一些东西.请帮忙.

My application uses multiple languages and it is really not possible for me to come up with a RegEx pattern to validate the string. For example, if I get the time string as "午前12時12分0秒", Moment JS should be able to validate this. I checked the source and found that time checking is not that strict in the library. I might have missed something. Please help.

推荐答案

在文档中,从2.3.0版开始,您可以传递第三个参数true,它打开严格解析"模式.

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

缺点是它必须完全匹配语言环境的格式(即作为第二个参数提供的语言环境)完全.由于LT在英语中等同于h:mm A,因此它将仅接受12个小时的时间,而没有秒.如果您经过24小时或秒,那么它将失败.

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

这篇关于有没有一种方法可以使用Moment JS验证时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆