jQuery - check proper time format - javascript

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.

Related

Regular expression for "-" in javascript

I want to know how can I get a regular expression for matching number, ., and - only.
I am using this:
/^[0-9\.'S]+$/
by this it working fine but not working for symbol "-".
You simply haven't used the literal dash - (or minus) in the regex. Try:
/^[0-9\.-]+$/
But if you want a proper number, you might want to use a more proper regex:
/^-?[0-9]+(?:\.[0-9]+)?$/
The first regex can accept things such as 3987----.... while the second will not accept it, but will accept things like -87.983274.
That's because - is not part of your character class. You are only using - in the class range (which only includes digits). Also, I don't know what the S and the ' are doing there:
/^[0-9.-]+$/
Also, I can promise you that after taking the time to read through this tutorial regular expressions will seem a lot less confusing to you.
Try the below regex.
/^-?[0-9\.]+$/

Regular expression in javascript to check time with date

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)/)

JScript: how to check if a string contains a specific word?

I am trying to find a way to check if a string contains a specific sequence of characters in JScript.
In my case, I am trying to see if the string is "DPObject" followed by a number. Such as "DPObject3" or "DPObject14".
Thank you!
if (/DPObject\d+/.test(string)) {....}
Javascript String has an indexOf method you can use to check if a String contains a particular substring .
If you need to test for patterns , like "DPObject" followed by an integer , probably you need to use Regexes . ( http://www.regular-expressions.info )
It's javascript , or js for short - not JScript .
Then you should use a regular expression. I think this would be something like :
var re = new RegExp("^DPObject([0-9]+)$");
re.test(someString);
This ensures there is at least only one digit after DPObject.
The "^" at the beginning is to ensure the string starts with DPObject. Check references on regexps for this kind of problems :)
edit: added "$" to mark the end of the string, the updated should be more "solid"
There are a couple of ways:
Use Javascripts indexOf method
Use Javascript Regular Expressions
Use JQuery's contains function
Regular expressions are the most powerful and elegant way of doing it. They syntax makes sense after a while (honestly). ;-)
Good luck.

Invalid regular expression error

I'm trying to retrieve the category part this string "property_id=516&category=featured-properties", so the result should be "featured-properties", and I came up with a regular expression and tested it on this website http://gskinner.com/RegExr/, and it worked as expected, but when I added the regular expression to my javascript code, I had a "Invalid regular expression" error, can anyone tell me what is messing up this code?
Thanks!
var url = "property_id=516&category=featured-properties"
var urlRE = url.match('(?<=(category=))[a-z-]+');
alert(urlRE[0]);
Positive lookbehinds (your ?<=) are not supported in JavaScript environments that do not comply with ECMAScript 2018 standard, which is causing your RegEx to fail.
You can mimic them in a whole bunch of different ways, but this might be a simpler RegEx to get the job done for you:
var url = "property_id=516&category=featured-properties"
var urlRE = url.match(/category=([^&]+)/);
// urlRE => ["category=featured-properties","featured-properties"]
// urlRE[1] => "featured-properties"
That's a super-simple example, but searching StackOverflow for a RegEx pattern to parse URL parameters will turn up more robust examples if you need them.
The syntax is messing up your code.
var urlRE = url.match(/category=([a-z-]+)/);
alert(urlRE[1]);
If you want to parse URL parameters, you can use the getParameterByName() function from this site:
http://james.padolsey.com/javascript/bujs-1-getparameterbyname/
In any case, as already mentioned, regular expressions in JavaScript are not plain strings:
https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions
var url = "property_id=516&category=featured-properties",
urlRE = url.match(/(category=)([a-z-]+)/i); //don't forget i if you want to match also uppercase letters in category "property_id=516&category=Featured-Properties"
//urlRE = url.match(/(?<=(category=))[a-z-]+/i); //this is a mess
alert(urlRE[2]);

How to use this regular expression in JavaScript?

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.

Categories