jquery - Javascript RegEx: validate date time - Stack Overflow

I am not very good with regex. I am being frustrated by a regular expression.Example: I have the follow

I am not very good with regex. I am being frustrated by a regular expression.

Example:

I have the following date time: 05/16/2013 12:00 am

I need a javascript regex that respect this format: mm/dd/yyyy hh:mm [am/pm]

 var dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;
if(!dateReg.test(inputVal)) {
    $(this).after('<span class="error error-keyup-5">Invalid date format.</span>');
}

But this code works only for date, not with time. Thanks for your help.

I am not very good with regex. I am being frustrated by a regular expression.

Example:

I have the following date time: 05/16/2013 12:00 am

I need a javascript regex that respect this format: mm/dd/yyyy hh:mm [am/pm]

 var dateReg = /^[0,1]?\d{1}\/(([0-2]?\d{1})|([3][0,1]{1}))\/(([1]{1}[9]{1}[9]{1}\d{1})|([2-9]{1}\d{3}))$/;
if(!dateReg.test(inputVal)) {
    $(this).after('<span class="error error-keyup-5">Invalid date format.</span>');
}

But this code works only for date, not with time. Thanks for your help.

Share Improve this question asked May 18, 2013 at 17:16 user2037696user2037696 1,1053 gold badges17 silver badges33 bronze badges 1
  • Do you want your date to be valid for each country? So for example 16/5/2013 12:00 ? – Niccolò Campolungo Commented May 18, 2013 at 17:22
Add a ment  | 

3 Answers 3

Reset to default 2

Your code snippet does only match the date, there are no atoms to match the time. Your regexp should be:

dateReg = /^[0,1]?\d\/(([0-2]?\d)|([3][01]))\/((199\d)|([2-9]\d{3}))\s[0-2]?[0-9]:[0-5][0-9] (am|pm)?$/

A regexp for am/pm time can be found here:

/^(0?[1-9]|1[012])(:[0-5]\d) [APap][mM]$/

You should not be parsing dates and times yourself. Find a good library to do it. d3.js contains fine support for parsing dates and times according to formats you specify. See https://github./mbostock/d3/wiki/Time-Formatting.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744393973a4572048.html

相关推荐

  • jquery - Javascript RegEx: validate date time - Stack Overflow

    I am not very good with regex. I am being frustrated by a regular expression.Example: I have the follow

    7天前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信