typescript - 如何使用时刻检查日期格式验证
问题描述
我的问题是关于输入日期格式的验证。我想要true
当且仅当日期完全以这种格式输入时,MM-DD-YYYY。但我的代码也只是用/(即用斜杠)验证日期。这意味着02-29/2020
,01/30-2020
甚至混合格式之类02/-29-/2020
的也是true
。此外,日、月和年必须分别采用 2 位和 4 位格式。我得到了帮助:
moment to validate date and time with custom format。我也创建了一个堆栈闪电战。这是我的代码:
validate(sDate: string, eDate: string) {
this.isValidDate = true;
this.startInvalid = false;
this.endInvalid = false;
this.dateErrors = new Set<string>();
const fromDate = moment(sDate, "MM-DD-YYYY");
console.log(fromDate.isValid());
const toDate = moment(eDate, "MM-DD-YYYY");
const currentDate = moment();
if (fromDate.isAfter(toDate)) {
this.dateErrors.add('Errors.StartDateMoreThanEndDate');
this.startInvalid = true;
this.isValidDate = false;
}
console.log(this.dateErrors);
return this.isValidDate;
}
这是否可能在瞬间实现,或者我将不得不为此编写一些正则表达式。如果我第一次使用时刻时我的整个实施是错误的,我很抱歉。
解决方案
我相信当你构建 时moment
,你会写这样的东西:
const myDate = moment(strDate, "MM-DD-YYYY", true)
最后一个变量设置strict parsing
为 true 的位置(请参阅此处的文档:https ://momentjs.com/docs/#/parsing/ )
推荐阅读
- html - Bootstrap 4 如何使“媒体对象”响应
- jquery - 默认表单事件完成后触发 jQuery 页面重定向
- google-meet - 如何使用 API 获取 Google Meet 链接
- python - 对 Keras Tensorflow 的高精度但不好的预测
- php - npm run watch 编译一次后停止编译(laravel 8 homestead + Vue)
- python - 如何将整数转换为特定的字节大小,然后结合起来在套接字上发送
- c# - AggregateException:某些服务无法构建
- linux - 使用 FFMPEG 以非常低的 FPS 进行屏幕捕获(视频截屏)
- xpath - Power Automate - Cloud Flow - 将 xpath 用于父节点属性
- sql-server - SQL Server 作业在调用 SSIS 包时挂起,直到代理重新启动