1

Java script function

<script language="JavaScript">

function checkdate(date1){
var validformat=/^\d{2}\/\d{2}\/\d{4} \d{2}\:\d{2}\:\d{2}$/ 
if(!validformat.test(date1.value)){
alert("Invalid Date");
 document.form.date1.value="";
}

}

The above is working well ! but I want to restrict the month and days accordingly.

my format = mm/dd/YYYY hh:mm:ss

Month should not be more than 12 and less than 1 and same , date should not be more than 31 and less than 1;

one thing more !

02/02/2013 00:00:00 is valid date but 2/2/2013 00:00:00 showing as a invalid date.

How to control these two situations ?

3 Answers 3

1

DateTime RegEx for the m/d/YYYY hh:mm:ss and mm/dd/YYYY hh:mm:ss

/^(0?[1-9]|1[012])\/(0?[1-9]|[12]\d|3[01])\/[12]\d{3} ([01]\d|2[0-3])\:[0-5]\d\:[0-5]\d$/

Explained demo: http://regex101.com/r/bS0gB6

Sign up to request clarification or add additional context in comments.

3 Comments

2/2/2013 00:00:00 and 2/2/2013 23:59:59 working, but 2/2/2013 12:30:20 not working!
you can remove your comments now @ShahidGhafoor
Can you please share me reg-ex of this format = YYYY-MM-DD hh:mm:ss
1

You can try the following method:

var comp = value.split('/');
var d = parseInt(comp[0], 10);
var m = parseInt(comp[1], 10);
var y = parseInt(comp[2], 10);
var date = new Date(y, m - 1, d);
var validDateFormat = false;
if (date.getFullYear() == y && date.getMonth() + 1 == m && date.getDate() == d) {
    validDateFormat = true;
}

if validDateFormat is true, the date is valid.

Comments

0

You can take a look at this website which allows you to create regular expressions for numeric ranges.

That being said, you should use numerical operators provided by the language your are using (Javascript) for numeric operations and not regular expressions.

Alternatively, you could use a DateTime Picker created in JQuery, as shown here.

2 Comments

var validformat=/^\d{2}\/\d{2}\/\d{4} \d{2}\:\d{2}\:\d{2}$/ can you append in this ? I have no nay idea regex, just copy paste from net
@ShahidGhafoor: The JQuery control allows you to specify the Date and Time format, like so: $('#dateTextBox').datetimepicker({ timeFormat: "HH:mm", dateFormat: "dd-mm-yy"}).

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.