简体   繁体   English

验证ISOString格式?

[英]Validate ISOString format?

How to validate if a field is a ISOString format? 如何验证字段是否为ISOString格式?

It work when I use valid date such as const create = '2018-08-02T02:07:49.214Z' but it break the script when I use const create = 'b'; 当我使用const create = '2018-08-02T02:07:49.214Z'等有效日期时,它可以工作,但是当我使用const create = 'b';时,它将破坏脚本const create = 'b';

Example: 例:

 //const create = '2018-08-02T02:07:49.214Z'; const create = 'b'; const dateParsed = new Date(Date.parse(create)) if(dateParsed.toISOString() === create){ console.log(dateParsed.getTime()) } else { console.log('invalid date') } 

I get an error RangeError: Invalid time value but expecting invalid date from console log. 我收到一个错误RangeError: Invalid time value但是期望控制台日志中的invalid date

To achieve expected result, add below condition 为了达到预期效果,请添加以下条件

!isNaN(dateParsed) && dateParsed.toISOString() === create

Issue: 问题:

console error is valid , as it throws error with toISOString() of invalid date 控制台错误有效,因为它抛出带有无效日期的toISOString()的错误

working code for reference 工作代码供参考

 const create = 'b'; const dateParsed = new Date(Date.parse(create)) if(!isNaN(dateParsed) && dateParsed.toISOString() === create){ console.log(dateParsed.getTime()) } else { console.log('invalid date') } 

new Date(Date.parse(create)) will return an Invalid Date, since Date.parse('b') returns NaN . 由于Date.parse('b')返回NaN ,所以new Date(Date.parse(create))将返回无效的Date。 I would point you towards this question: Detecting an "invalid date" Date instance in JavaScript , which provides a couple ways to checking if a date is valid or not. 我将向您指出这个问题: 在JavaScript中检测“无效日期” Date实例 ,它提供了两种方法来检查日期是否有效。

At least in this example case, it doesn't seem like ISO format is strictly required, but you should be able to construct a regex to at least match the structure (there may be other requirements for a truly valid ISO datestring, I'm not sure off the top of my head). 至少在此示例情况下,似乎并非严格要求ISO格式,但是您应该能够构造一个正则表达式以至少与结构匹配(对于真正有效的ISO日期字符串可能还有其他要求,我是不确定从我的头顶掉)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM