javascript 为 YYYY-MM-DD HH:MM 编写 JS 正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28126345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:27:12  来源:igfitidea点击:

Writing JS regex for YYYY-MM-DD HH:MM

javascriptregex

提问by user3355028

I'm new with JS and I need to validate a date in a form. The date field is a regular text field. The name of the date field called "date". How can I validate if the date is from the format of YYYY-MM-DD HH:MM with a simple regular expression in JS?

我是 JS 新手,我需要验证表单中的日期。日期字段是一个普通的文本字段。日期字段的名称称为“日期”。如何使用 JS 中的简单正则表达式验证日期是否来自 YYYY-MM-DD HH:MM 格式?

Thanks

谢谢

回答by Always Sunny

Try this way to validate your date in YYYY-MM-DD HH:MMformat

尝试以这种方式验证您的日期YYYY-MM-DD HH:MM格式

   var re = /[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1]) (2[0-3]|[01][0-9]):[0-5][0-9]/;
var str = '2014-02-04 12:34';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

enter image description here

在此处输入图片说明

SEE DEMO :https://www.regex101.com/r/rT6vJ4/1

看演示:https: //www.regex101.com/r/rT6vJ4/1

回答by Ben Tayaa

you can try this also :

你也可以试试这个:

var myRegExp=/^\d{4}-[0-1][0-2]-[0-3]\d\s([0-1][0-9]|2[0-3]):[0-5]\d$/;
var date="2015-01-01 10:10";

if(date.match(myRegExp)){
   console.log("Good format");
}

Infos about the regular expression :

关于正则表达式的信息:

  • " ^ " : assert position at start of the string
  • " \d{x} " : match a digit Exactly x times
  • " - " : matches the character - literally
  • " [range] " : match a single character present in the rang
  • " \s " : match any white space character [\r\n\t\f ]
  • " $ " : assert position at end of the string
  • " ^ " : 断言字符串开头的位置
  • " \d{x} " : 匹配一个数字正好 x 次
  • “ - ” :匹配字符 - 字面意思
  • " [range] " : 匹配范围内的单个字符
  • " \s " : 匹配任何空白字符 [\r\n\t\f ]
  • " $ " : 断言字符串末尾的位置

You can test it by yourself at : http://codepen.io/anon/pen/XJgeeV

您可以在以下网址自行测试:http: //codepen.io/anon/pen/XJgeeV

[ Updated following David Faber's advice ]

[根据 David Faber 的建议更新]

回答by Yagiz

When I googled it, there are some great examples such as Date Form Validation

当我用谷歌搜索时,有一些很好的例子,比如日期表单验证