Reputation: 4660
I am new to regex and have a question. I am validating a date/time text input and only want to allow characters that fit an exact pattern. This is the format:
Mar 19, 2014 at 2:00am
Obviously the date (in this case "19") and the hour (in this case "2") could be one or two characters long. On Javascript keyup, I need a regex expression that removes all characters that do not exactly fit this pattern. How can I do this with regex? This is the exact pattern:
I do not care that it is a valid date. I simply need the entered text to fit this format.
Thank you for your help!
Upvotes: 0
Views: 1525
Reputation: 11116
[A-Za-z]{3}\s\d{1,2},\s\d{4}\sat\s\d{1,2}:\d{2}(am|pm)
will match your requirement exactly
demo here : http://regex101.com/r/rU8xT0\
using with js
var str = "Mar 1, 2014 at 2:00pm";
if( /[A-Za-z]{3}\s\d{1,2},\s\d{4}\sat\s\d{1,2}:\d{2}(am|pm)/.test(str)){
console.log("pass");
}
else{
console.log("fail");
}
and this is exactly what you want, this will check for values which are not correct and highlight accordingly, I am using jquery to add and remove the class
$("#text").keyup(function () {
if (/[A-Za-z]{3}\s\d{1,2},\s\d{4}\sat\s\d{1,2}:\d{2}(am|pm)/.test($(this).val())) {
$(this).removeClass('error');
$(this).addClass('good');
} else {
$(this).removeClass('good');
$(this).addClass('error');
}
})
for OPs special requirement in js
var str = "Mar 1, 2014 at 2:00pmaur bahut sara kachra";
var res = str.replace(/([A-Za-z]{3}\s\d{1,2},\s\d{4}\sat\s\d{1,2}:\d{2}(am|pm)).*/, '$1');
console.log(res);
fiddle demo here : http://jsfiddle.net/kq65X/1/
Upvotes: 1