Reputation: 377
I am trying this to validate the date.However I am not too sure about what is wrong with this.
Note- I my application there is no space between mm(minuted) and AM/PM.
var date = '21/01/13 6:40AM';
var myRegex = /0?[0-31]\d\/0?[0-12]\d\/\d{2} [0-11]\d:[0-59]\d[AP][M]/;
if (myRegex.test(date)){
// Ok to proceed
}
I tried the following by breaking the date and time separately i.e the following combination
var date = '21/01/13'
var myRegex = /0?[0-31]\d\/0?[0-12]\d\/d{2}/;
However for the time part i.e 6:40AM.I am not able to validate it with
var myRegex = /[0-11]\d:[0-59]\d[AP][M]/;
Could you please help me out.
Upvotes: 1
Views: 168
Reputation: 147403
One way to validate date and time strings is to create a date object and see if the parts match, e.g.
function validateDateString(s) {
var b = s.split(/[\/ :]/g);
var ap = s.substring(-2).toLowerCase();
var h = parseInt(b[3], 10) + (ap == 'am'? 0 : 12);
var min = parseInt(b[4],0);
var y = +b[2] + (b[2] < 50? 2000 : 1900);
var d = new Date(y, --b[1], b[0], h, min, 0, 0);
var apValid = /am|pm/.test(ap);
// Only need to test two parts of date and hours
return d.getMonth() == b[1] && d.getDate() == b[0] && d.getHours() == h && apValid;
}
console.log(validateDateString('21/01/13 6:40AM')); // true
You could use a regular expression too, and if ES5 compliant browsers are all you need to support you could reformat the string as an ISO 8601 compliant string a pass it to Date.parse. But that won't work in many browsers in use.
Upvotes: 0
Reputation: 383
Try This :
var regex = /^([0-11]\d):([0-59]\d)\s?(?:AM|PM)?$/i;
Will work for : "06:40am"
Upvotes: 1
Reputation: 2032
Try This One. Leap year supported. example: http://jsfiddle.net/Vk268/
^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$
Upvotes: 1
Reputation: 11824
I suggest you to check actual validity not just syntax. check this post which uses datejs
Jquery DateJs, is there validation for full date?
Upvotes: 0