2

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.

1
  • Do you want your date to be valid for each country? So for example 16/5/2013 12:00 ? Commented May 18, 2013 at 17:22

3 Answers 3

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)?$/
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Comments

1

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.com/mbostock/d3/wiki/Time-Formatting.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.