Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Regex: validating a double/float

Here's the pattern I'm working on:

var re = /(\d{1,2}\.(?=\d{1,2}))/;

What I would like for this to return is a one or two digit number (which will never be greater than 24, since it is for a time mgmt app), which may or may not be followed by a decimal point with either one or two trailing digits, but not more than two.

I'm not sure about the parenthetical substring match mixed with the lookahead. I just guessed and nested them. Ultimately, if my syntax is okay, I think the only thing I am missing is how to suggest that the pattern may or may not have leading digits, and may or may not contain a decimal with trialing digits.

Let me know if you need more info.

Update, Examples:

We are only dealing with time, and no more time than can occur in a single day. 24 would be the highest input.

Valid:

23.75
1.4 
1
0.5 
0
.2

Invalid:

1.897
%#$#@$#
Words
other characters

Newest Update:

Since this is a decimal, 23.75 works. We are not counting minutes, but rather fractions of hours.

Also, for the record, I tried validating using methods and conditionals, and it was letting letters pass through after the decimals. I have made the decision to go with regex.

like image 624
eightArmCode Avatar asked Dec 12 '22 14:12

eightArmCode


1 Answers

If "any number given will be less than 24", so that doesn't need to be separately tested for, then the following expression will work.

^\d{0,2}(\.\d{0,2}){0,1}$

See http://rubular.com/r/YDfHr5T5sQ

Tested against:

23.75             pass
1.4               pass
1                 pass
0.5               pass
0                 pass
.2                pass
1.897             fail
%#$#@$#           fail
Words             fail
other characters  fail

Explanation:

^             start matching at the start of the string
\d{0,2}       look for zero to two digits
(   ){0,1}$   look for this next thing zero or one time, then the end of the string
\.\d{0,2}     match exactly one decimal followed by up to two digits

Note - this regex does match the "empty string". You might want to test for that separately if there's a chance that will somehow make its way to this expression...

Simple code to test in your javascript:

var str = "12.345";
var m = str.match(/^\d{0,2}(?:\.\d{0,2}){0,1}$/);
var goodTime;
if (!m) {
    alert(str + " is not a good time");
}
else {
    goodTime = m[0];
    alert("found a good time: " + goodTime);
}

Note - I made a tweak to the regex - adding ?: in the "bit after the decimal" group. This just means "match but don't capture" so the result will return only the match m[0] and not the group .34 in m[1]. It doesn't actually matter since I assign goodTime the value in m[0] (but only if it's a good time). You can see this in action here

like image 183
Floris Avatar answered Dec 31 '22 11:12

Floris