I am validating dates using regular expression in javascript. The regular expression I am using is
/^(((((0?[1-9])|(1\d)|(2[0-8]))\/((0?[1-9])|(1[0-2])))|((31\/((0?[13578])|(1[02])))|((29|30)\/((0?[1,3-9])|(1[0-2])))))\/((20[0-9][0-9])|(19[0-9][0-9])))|((29\/02\/(19|20)(([02468][048])|([13579][26]))))$/
This matches dates accurately but it would match values such as
1/1/2001ff even though I am using $ to mark the end of string.
But if I give values like ff1/1/2001 it would invalidate it. So it's considering the start of the string and ignore the end of string part.
Does anyone know the reason for this.
From: Detecting an "invalid date" Date instance in JavaScript
if ( Object.prototype.toString.call(d) === "[object Date]" ) {
// it is a date
if ( isNaN( d.getTime() ) ) { // d.valueOf() could also work
// date is not valid
}
else {
// date is valid
}
}
else {
// not a date
}
Logically, it makes much more sense to check if the date is valid rather than using a regex to match a date. However, if you're trying to search for dates, your regex still works (I tested it in Notepad++ find for example.) Other than that, like the comment said, there's no reason to have such a complicated regex.
As correctly pointed out by Dracs, the issue was with missing brackets. Thank you very much for pointing that out.
The reason for not using javascript date object is we need only to allow mm/dd/yyyy format in the textbox. So it would be easy to use a regex to validate textbox.
Related
Im trying to create regex pattern in javascript to validate datetime format yyyy-MM-dd hh:mm:ss
/([0-2][0-9]{3})\-([0-1][0-9])\-([0-3][0-9]) ([0-5][0-9])\:([0-5][0-9])\:([0-5][0-9])(([\-\+]([0-1][0-9])\:00))/
here is an example on jsfiddle
but its not working when i test it against this date time 2017-08-31 01:22:34
can anybody help me to know whats wrong in my pattern
Thank you
It's because the pattern currently requires, rather than makes optional, the timezone modifier, which isn't present in the example date you gave.
Change the last part to:
( ([\-\+]([0-1][0-9])\:00))?
Also:
your hours sub-group is matching 0-59 rather than 0-23.
you're escaping a number of things you don't need to, e.g. : and -
the pattern allows for invalid dates e.g. 39 as a day.
Revision:
/^([0-2][0-9]{3})\-(0[1-9]|1[0-2])\-([0-2][0-9]|3[0-1]) ([0-1][0-9]|2[0-3]):([0-5][0-9])\:([0-5][0-9])( ([\-\+]([0-1][0-9])\:00))?$/
Note this will not account for invlaid dates in certain months e.g. 30th February. That means either making the pattern more complicated or using something better suited than REGEX for date validation.
It's because of the last part which should be optional (([\-\+]([0-1][0-9])\:00))?
Here is a demo
var a = /([0-2][0-9]{3})-([0-1][0-9])-([0-3][0-9]) ([0-5][0-9]):([0-5][0-9]):([0-5][0-9])(([\-\+]([0-1][0-9])\:00))?/;
console.log('2017-08-31 01:22:34'.match(a))
BTW, you don't have to escape :. - should be escaped only when used inside brackets []
In java, we can use like below and also you can take this pattern for javascript
private static Pattern DATE_PATTERN = Pattern.compile(".*?\[0-9\]{4}-(0\[1-9\]|1\[0-2\])-(0\[1-9\]|\[1-2\]\[0-9\]|3\[0-1\]) (2\[0-3\]|\[01\]\[0-9\]):\[0-5\]\[0-9\]:\[0-5\]\[0-9\]");
public void test() {
if(!DATE_PATTERN.matcher(line.trim()).matches()) {
//code here
}
}
If you want to check only date then remove *? from the pattern
I encounter problem when parsing date via native JS Date object.
new Date("I'm really clever date 8745")
This expression returns valid Date which was pretty shocking for me. How to prevent this special behavior ?
EDIT: Date interprets last number as year ...
EDIT: Chrome, version (48.0.2564.116)
EDIT: Expected format is "2016-03-20T18:05:53.485Z" (JSON stringify)
if you intend to "match" any valid date (eg. christmas...), it is far from simple. if istead you want to allow only some format type, i'll go with regexp. here a simple not very extended example:
function isprobablyavaliddate(str){
var allowed = /\d{4}[\\\/-]{1}\d{2}[\\\/-]{1}\d{2}/
//example allowed date formats: yyyy-mm-dd, yyyy/mm/dd
return allowed.test(str)
}
var testString = "I'm really clever date 8745"
//catch valid string before doing anything with a date...
if ( isprobablyavaliddate(testString) ) mydate = new Date(testString)
else ...
for your valid format requested in your edit: /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z/ (the ^ is for match initial character)
I used regex for testing if string is valid ISO date.
/(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/;
Works perfectly.
I have an input field where the user enters a time in format mm:hh. The format is specified inside the field (default value 09:00) but I still want to perform a client-side check to see if the format is correct.
Since the existing client-side validation is in jQuery, I'd like to keep this in jQuery as well.
I'm mainly a PHP programmer so I need some help writing this one in an optimal manner.
I know I can check each individual character (first two = digits, third = ':', last two = digits) but is there a way to do it more elegantly, while also checking the hour count is not larger than 23 and the minute count isn't larger than 59?
In PHP I would use regular expressions, I assume there's something similar for jQuery?
Something like this makes sense to me:
([01]?[0-9]|2[0-3]):[0-5][0-9]
But I'm not too familiar with jQuery syntax so I'm not sure what to do with it.
you can use regex in JavaScript too:
http://www.w3schools.com/jsref/jsref_obj_string.asp
use
.search() - http://www.w3schools.com/jsref/jsref_search.asp
or .match() - http://www.w3schools.com/jsref/jsref_match.asp
or .replace() - http://www.w3schools.com/jsref/jsref_replace.asp
EDIT:
<script>
var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
var correct = ($('input').val().search(regexp) >= 0) ? true : false;
</script>
EDIT2:
here the documentation of regexpobject in javascript:
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
<script>
var regexp = /([01][0-9]|[02][0-3]):[0-5][0-9]/;
var correct = regexp.test($('input').val());
</script>
EDIT3:
fixed the regexp
In JavaScript, regexes are delimited by /. So you would do...
var isValidTime = /([01]?[0-9]|2[0-3]):[0-5][0-9]/.test(inputString);
Your regex seems to make sense for validating any 24H time in HH:mm format. However as I state in my comment under Andreas's answer - this will return true if any part of the string matches. To make it validate the entire string, use anchors to match the start and end of the string also eg...
var isValidTime = /^([01]?[0-9]|2[0-3]):[0-5][0-9]$/.test(inputString);
To actually pull the matches you would need to use the string.match JS function.
Oh - and please be aware that jQuery is Javascript - it's just a library of very useful stuff! However this example contains no reference to the jQuery library.
In JavaScript you can use yourstring.match(regexp) to match a string against a regular expression.
I have very limited RegEx-experience, so I cant help you with the pattern, but if you have that set .match() should be all it takes.
A different approach, but using an extra javascript lib instead of regular expressions:
var valid = moment(timeStr, "HH:mm", true).isValid();
I guess if you already use moment.js in your project, there's no downside.
And since you didn't specifically request an answer using regular expressions, I think it's valid to mention.
I need to check whether the text contains a date part with it.
for ex: mytext_12/26/2011_11:51_AM or someText_12/26/2011_13:51_PM have a date part it returns true.
I am not too good with expressions so looking for one. the format of the date - time part is fixed.
i got a way out for it but failing for time .
var containsDate = ~str.search(/\d{1,2}\/\d{1,2}\/\d{4}/);
it checks the date part perfectly but when i am trying for the time part i am messing it up some where .
_\d{1,2}:\d{2}_(?:AM|PM) this is the part for time but i am not able to generate the final regex by combining this two.
Try,
.search(/[0-9]{2}\/[0-9]{2}\/[0-9]{4}_[0-9]{2}:[0-9]{2}_(AM|PM)/)
A good resource for regex,
MDN:Regular Expressions
Try,
.search(/\d+\/\d+\/\d{4}_\d+:\d+_(AM|PM)/)
I am trying to use the following regular expression to test for a valid date.
^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$
which I got from
http://regexlib.com/REDetails.aspx?regexp_id=1071
My JavaScript test code is:
var date='1/1/1965';
var re = new RegExp('^(((0?[1-9]|1[012])/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$');
alert(re.test(date));
I keep getting "false" rather than "true" for this valid test date.
Try this:
var date='1/1/1965';
var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])\/(29|30)|(0?[13578]|1[02])\/31)\/(19|[2-9]\d)\d{2}|0?2\/29\/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/;
alert(re.test(date));
Your problem might be escaping of the slashes.
There are 2 ways you can insert a regexp in javascript. 1st way is just put it in forward slashes, and the second way, which is the way you are doing it is with RegExp object, which means that you then have to include the regexp string itself in the JavaScript code as a string.
And as every other string in Javascript which contains special characters like backward slashes (which your regexp does), you have to escape them with yet another backslash.
So basically just replace every backslash in your code with double backslash (\\) and you should be fine.
Just put it in forward-slashes:
var re = /^(((0?[1-9]|1[012])\/(0?[1-9]|1\d|2[0-8])|(0?[13456789]|1[012])/(29|30)|(0?[13578]|1[02])/31)\/(19|[2-9]\d)\d{2}|0?2/29/((19|[2-9]\d)(0[48]|[2468][048]|[13579][26])|(([2468][048]|[3579][26])00)))$/
Now, while that'll get you a regular expression to use, I have to say that this may be one of the silliest applications of a regex ever. You'd be way better off just instantiating a JavaScript "Date" object and using it's surprisingly friendly API to check what you need to check.
If you instantiate a JavaScript "Date" object with a bogus date (like Februrary 30), it'll just roll to the actual date that sort-of corresponds to the bogus date; in other words, it carries over the bogus days into the next month. Thus, if you just hold on to the month and day, and create a "Date" instance, you can know that if the month and day that the "Date" instance gives you when you ask are different from the ones you fed it, then the original date must have been unreal.