javascript regular expressions - javascript

Help me with regular expressions. I need to check the text on the hour and minute. That is the first case, the text can be from 0 to 12. In the second case, the text can be from 1 to 60.
this is my code:
var hourRegEx = /^([0-9]{2})$/; //You can fix this line of code?
$(document).ready(
function(){
$('form.form').submit(function(){
if( $('input.hour').val().match(hourRegEx) ){
return true;
}
return false;
});
});
In my case, the code says that, for example 52, too, the correct answer

I would do this with parseInt and numeric checking:
var hour = parseInt($('input.hour').val(), 10);
if((hour >= 0) && (hour <= 11)){
return true;
}

If what you are inherently doing is comparing numbers you really shouldn't use a regex
I would do this:
var numericRegEx = /^[0-9]+$/;
$(document).ready(
function(){
$('form.form').submit(function(){
var hourVal = $('input.hour').val();
if( hourVal.match(numericRegEx) && parseInt(hourVal) <= 11){
return true;
}
return false;
});
});
This may be overly complicated; if I was doing this I would just use parseInt, but the original code would return false for values such as "11blah" so some regex functionality is still used to check the entire string is an integer.

Why not convert it to integer and use <? Regex is not a substitution for integer arithmetics.

Use: /^([0-9]|10|11|12)$/. It's short enough, and very clear :)
Edit: or, if #Jamiec is right and you're mistaken about the numbers, /^([0-9]|10|11)$/
For minutes, use: /^([0-9]|[1-5][0-9])$/.
Edit 2: ah wait, 1 to 60. Use this:
/^([1-9]|[1-5][0-9]|60)$/
and for hours 1-12, if you need it:
/^([1-9]|10|11|12)$/ or /^([1-9]|1[0-2])$/

The RegEx for testing a number between 0 and 12 would be along the lines of ^([0-9]|1[012])$ and for the minutes: ^[1-9]|[2-5][0-9]$.
I wouldn't recommend it though. Personally, I'd use parseInt to get the value as a number. You can check it's a valid number because parseInt will return NaN if it isn't. Then you can do your range check.
var hourVal = parseInt($('input.hour').val(),10),
minVal = parseInt($('input.minute').val(),10);
if(hourVal && hourVal >=0 and hourVal <= 12){
// hour valid
}
if(minVal && minVal >=1 and minVal <= 60){
// min valid
}

This should handle also cases where the user inputs 00-09:
/^(0?[0-9]|1[0-2])$/

This:
[1-9]|1[0-2] will match the hour ( 1 .. 12 )
[1-9]|[1-5][0-9]|60 will match the minutes ( 1 .. 60 )
if you want to match 0 .. 11 and 0 .. 59 do this
[0-9]|1[0-1] will match the hour ( 0 .. 11 )
[0-9]|[1-5][0-9] will match the minutes ( 0 .. 59 )
if you want to match 00 .. 11 and 00 .. 59 do this
0[0-9]|10|11 will match the hour ( 00 .. 11 )
[0-5][0-9] will match the minutes ( 00 .. 59 )

Using regex is not viable for this case. You should compare integer instead, because '1', '01', '001' are valid too.
i recommand this kind of snippet
val = parseInt($('input.hour').val());
if (val >= 0 && val <= 12)
// is valid ...

Related

RexExp min and max

I am trying to validate min 1 and max 59 with the following regexp but not working as expected.
^[1-5]?[1-9]$
What is wrong with the expression?
It's work: ^([1-5][0-9]|[1-9])$ (#Tushar)
if (/^([1-5][0-9]|[1-9])$/.test(number)) {
// Successful match
} else {
// Match attempt failed
}
The better/faster way (without regex):
function validate(number) {
number = parseInt(number);
return number > 0 && number < 60;
}
for (var i = 0; i < 65; i++) {
console.log(validate(i));
}
Tested:
Everyone busy trying to provide a solution missed the real question OP asked.
What is wrong with the expression?
Well here is your regex: ^[1-5]?[1-9]$
What you are trying to do is match a number having first digit (optional) in range 1 to 5 and second digit in range 1-9. And since you want to match number from 1 to 59, you will be missing is numbers like 10,20,30,40,50 as pointed out in one comment.

Javascript validation on Floating values

How to do decimal validation using javascript?
There is a text box which should accept only 24.00 or 24 or any value less than 24.00.
The text box also must allow if 23.99 is entered.
I tried it this way:
if (document.forms[0].hours!= undefined) {
var val = document.forms[0].hours.value;
if (val .match(/^\d{0,6}(?:\.\d{0,2})?$/)) {
alert("Invalid" +'${payType}'+" Hours. The hours entered can not have more than 2 decimal places or should be in the range of 0 to 24 ");
submitted=false;
return false;
}
}
The values can be: 1.00 or 12.25 or 1.25 or 23.99 or 24 but not above these values. Any number below 24.00 or 24.
If you prefer doing it with regex try this
^(0+)?(24(\.00?)?|(\.00?)?|\.[0-9]+|0?[0-9](\.[0-9]{0,2})?|(0+)?[0-2][0-3](\.[0-9][0-9]?)?)$
Tested on all the values below
0.0
4.00
4.01
024.0
5.8
2.95
10.5
10.00
023.9
011
09.89
09
8.67
24
24.00
24.0
23.99
0.00
0
.5
.55
6
24.01 // fail
13.90
78.23 // fail
1.56
0.06
25.00 // fail
23.99
41.00 // fail
Demo
The section below isn't related to the answer but rather to the comments below. #Anto these are just a few of online resources on regex. Have fun ;)
Free online books (google for these books)
Mastering Regular Expressions, 3rdEdition
Introducing Regular Expressions
Regular Expression Pocket Reference, 2nd Edition
Regular Expressions Cookbook
Good websites
http://www.regular-expressions.info
http://www.rexegg.com
http://regexlib.com
http://overapi.com/regex/
Online regex tester
http://regex101.com/
You could try the below regex,
^(?:24\.00|24|(?:[0][1-9]|[1][0-9]|2[0-3])\.[0-9][0-9])$
DEMO
OR
If you don't want 0 before the digit then you could try the below
^(?:24\.00|24|(?:[1-9]|[1][0-9]|2[0-3])\.[0-9][0-9])$
DEMO
you can reverse thinking
allow any number above 24.00 or 24
var reg = /^(24\.(0[1-9]|[1-9]\d?)|([3-9]\d|[^0]\d{2,9}|2[5-9])(\.\d{1,2})?)$/
3.33 fail
23.00 ...
24 ...
24.00 ...
0.00 ...
0 ...
24.01 pass
34.01 ...
34 ...
120.18 ...
if (document.forms[0].hours!= undefined) {
var val = document.forms[0].hours.value;
if (!reg.test(val)) {
alert("Invalid" +'${payType}'+" Hours. The hours entered can not have more than 2 decimal places or should be in the range of 0 to 24 ");
submitted=false;
return false;
}
}
You don't need regular expression for this at all.
In fact it would be a lot simpler to just do this:
if (document.forms[0].hours!= undefined) {
var val = parseFloat(document.forms[0].hours.value);
// Get the number of decimals
var a = val.toString().split(".");
var decimals = a.length > 1 ? a[1].length : 0;
if (isNaN(val) || val < 0 || val > 24 || decimals > 2) {
alert("Invalid" +'${payType}'+" Hours. The hours entered can not have more than 2 decimal places or should be in the range of 0 to 24 ");
submitted=false;
return false;
}
}

JQuery validate regular expression to get interest rate

I want regular expression to get rate of interest. I am wanting to accept following things:
Ex:
0
0.4
0.44
4
44
4.00
44.00
4.2
4.22
44.22
Min 0 and Max 99.99
It must have to accept numeric as well as decimal values but not more than 99.99. Also it should take decimal after first or second digit and after third digit it should display an error message.
I am trying this regular expression but its not perfectly working for me.
$.validator.addMethod('interest', function(value, element) {
return this.optional(element) || /\d{1,2}\.?\d{0,4}/.test(value);
}, 'Please specify a valid data');
Any help would be appreciated.
A regex to match all of those numbers between 0 and 99.99 would be:
^\d{1,2}(\.\d{1,2})?$
so you're pretty close, but your regex matches 0 to 4 digits after the .
EDIT: forgot ^$
Why mess with regexes if you can simply check for the value:
var input = parseFloat(value)
return !isNaN(input) && input >= 0 && input < 100;
If you want to make sure there are at most 2 decimal placed in the string, the check will be a little longer:
return !isNaN(input) &&
input >= 0 &&
input < 100 &&
!(value.split('.')[1] && value.split('.')[1].length > 2);
If you use regex you will end up having two problems. Try:
function validateStuff(input) {
return ($.isNumeric(input) && input >= 0 && input <= 99.99);
}
// Testing:
console.log(validateStuff(5));
console.log(validateStuff("Hello"));
console.log(validateStuff(100));
console.log(validateStuff(99.99));
DEMO

javascript regular expression to check for IP addresses

I have several ip addresses like:
115.42.150.37
115.42.150.38
115.42.150.50
What type of regular expression should I write if I want to search for the all the 3 ip addresses? Eg, if I do 115.42.150.* (I will be able to search for all 3 ip addresses)
What I can do now is something like: /[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}\.[0-9]{1-3}/ but it can't seems to work well.
Thanks.
May be late but, someone could try:
Example of VALID IP address
115.42.150.37
192.168.0.1
110.234.52.124
Example of INVALID IP address
210.110 – must have 4 octets
255 – must have 4 octets
y.y.y.y – only digits are allowed
255.0.0.y – only digits are allowed
666.10.10.20 – octet number must be between [0-255]
4444.11.11.11 – octet number must be between [0-255]
33.3333.33.3 – octet number must be between [0-255]
JavaScript code to validate an IP address
function ValidateIPaddress(ipaddress) {
if (/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress)) {
return (true)
}
alert("You have entered an invalid IP address!")
return (false)
}
Try this one, it's a shorter version:
^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$
Explained:
^ start of string
(?!0) Assume IP cannot start with 0
(?!.*\.$) Make sure string does not end with a dot
(
(
1?\d?\d| A single digit, two digits, or 100-199
25[0-5]| The numbers 250-255
2[0-4]\d The numbers 200-249
)
\.|$ the number must be followed by either a dot or end-of-string - to match the last number
){4} Expect exactly four of these
$ end of string
Unit test for a browser's console:
var rx=/^(?!0)(?!.*\.$)((1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/;
var valid=['1.2.3.4','11.11.11.11','123.123.123.123','255.250.249.0','1.12.123.255','127.0.0.1','1.0.0.0'];
var invalid=['0.1.1.1','01.1.1.1','012.1.1.1','1.2.3.4.','1.2.3\n4','1.2.3.4\n','259.0.0.1','123.','1.2.3.4.5','.1.2.3.4','1,2,3,4','1.2.333.4','1.299.3.4'];
valid.forEach(function(s){if (!rx.test(s))console.log('bad valid: '+s);});
invalid.forEach(function(s){if (rx.test(s)) console.log('bad invalid: '+s);});
If you are using nodejs try:
require('net').isIP('10.0.0.1')
doc net.isIP()
The regex you've got already has several problems:
Firstly, it contains dots. In regex, a dot means "match any character", where you need to match just an actual dot. For this, you need to escape it, so put a back-slash in front of the dots.
Secondly, but you're matching any three digits in each section. This means you'll match any number between 0 and 999, which obviously contains a lot of invalid IP address numbers.
This can be solved by making the number matching more complex; there are other answers on this site which explain how to do that, but frankly it's not worth the effort -- in my opinion, you'd be much better off splitting the string by the dots, and then just validating the four blocks as numeric integer ranges -- ie:
if(block >= 0 && block <= 255) {....}
Hope that helps.
Don't write your own regex or copy paste! You probably won't cover all edge cases (IPv6, but also octal IPs, etc). Use the is-ip package from npm:
var isIp = require('is-ip');
isIp('192.168.0.1');
isIp('1:2:3:4:5:6:7:8');
Will return a Boolean.
Try this one.. Source from here.
"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b"
Below Solution doesn't accept Padding Zeros
Here is the cleanest way to validate an IP Address, Let's break it down:
Fact: a valid IP Address is has 4 octets, each octets can be a number between 0 - 255
Breakdown of Regex that matches any value between 0 - 255
25[0-5] matches 250 - 255
2[0-4][0-9] matches 200 - 249
1[0-9][0-9] matches 100 - 199
[1-9][0-9]? matches 1 - 99
0 matches 0
const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';
Notes: When using new RegExp you should use \\. instead of \. since string will get escaped twice.
function isValidIP(str) {
const octet = '(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?|0)';
const regex = new RegExp(`^${octet}\\.${octet}\\.${octet}\\.${octet}$`);
return regex.test(str);
}
If you want something more readable than regex for ipv4 in modern browsers you can go with
function checkIsIPV4(entry) {
var blocks = entry.split(".");
if(blocks.length === 4) {
return blocks.every(function(block) {
return parseInt(block,10) >=0 && parseInt(block,10) <= 255;
});
}
return false;
}
A short RegEx: ^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$
Example
const isValidIp = value => (/^(?:(?:^|\.)(?:2(?:5[0-5]|[0-4]\d)|1?\d?\d)){4}$/.test(value) ? true : false);
// valid
console.log("isValidIp('0.0.0.0') ? ", isValidIp('0.0.0.0'));
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));
console.log("isValidIp('192.168.0.1') ? ", isValidIp('192.168.0.1'));
console.log("isValidIp('110.234.52.124' ? ", isValidIp('110.234.52.124'));
console.log("isValidIp('115.42.150.37') ? ", isValidIp('115.42.150.37'));
console.log("isValidIp('115.42.150.38') ? ", isValidIp('115.42.150.38'));
console.log("isValidIp('115.42.150.50') ? ", isValidIp('115.42.150.50'));
// Invalid
console.log("isValidIp('210.110') ? ", isValidIp('210.110'));
console.log("isValidIp('255') ? ", isValidIp('255'));
console.log("isValidIp('y.y.y.y' ? ", isValidIp('y.y.y.y'));
console.log(" isValidIp('255.0.0.y') ? ", isValidIp('255.0.0.y'));
console.log("isValidIp('666.10.10.20') ? ", isValidIp('666.10.10.20'));
console.log("isValidIp('4444.11.11.11') ? ", isValidIp('4444.11.11.11'));
console.log("isValidIp('33.3333.33.3') ? ", isValidIp('33.3333.33.3'));
/^(?!.*\.$)((?!0\d)(1?\d?\d|25[0-5]|2[0-4]\d)(\.|$)){4}$/
Full credit to oriadam. I would have commented below his/her answer to suggest the double zero change I made, but I do not have enough reputation here yet...
change:
-(?!0) Because IPv4 addresses starting with zeros ('0.248.42.223') are valid (but not usable)
+(?!0\d) Because IPv4 addresses with leading zeros ('63.14.209.00' and '011.012.013.014') can sometimes be interpreted as octal
Simple Method
const invalidIp = ipAddress
.split(".")
.map(ip => Number(ip) >= 0 && Number(ip) <= 255)
.includes(false);
if(invalidIp){
// IP address is invalid
// throw error here
}
Regular expression for the IP address format:
/^(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])\.(\d\d?)|(1\d\d)|(0\d\d)|(2[0-4]\d)|(2[0-5])$/;
If you wrtie the proper code you need only this very simple regular expression: /\d{1,3}/
function isIP(ip) {
let arrIp = ip.split(".");
if (arrIp.length !== 4) return "Invalid IP";
let re = /\d{1,3}/;
for (let oct of arrIp) {
if (oct.match(re) === null) return "Invalid IP"
if (Number(oct) < 0 || Number(oct) > 255)
return "Invalid IP";
}
return "Valid IP";
}
But actually you get even simpler code by not using any regular expression at all:
function isIp(ip) {
var arrIp = ip.split(".");
if (arrIp.length !== 4) return "Invalid IP";
for (let oct of arrIp) {
if ( isNaN(oct) || Number(oct) < 0 || Number(oct) > 255)
return "Invalid IP";
}
return "Valid IP";
}
Throwing in a late contribution:
^(?!\.)((^|\.)([1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d))){4}$
Of the answers I checked, they're either longer or incomplete in their verification. Longer, in my experience, means harder to overlook and therefore more prone to be erroneous. And I like to avoid repeating similar patters, for the same reason.
The main part is, of course, the test for a number - 0 to 255, but also making sure it doesn't allow initial zeroes (except for when it's a single one):
[1-9]?\d|1\d\d|2(5[0-5]|[0-4]\d)
Three alternations - one for sub 100: [1-9]?\d, one for 100-199: 1\d\d and finally 200-255: 2(5[0-5]|[0-4]\d).
This is preceded by a test for start of line or a dot ., and this whole expression is tested for 4 times by the appended {4}.
This complete test for four byte representations is started by testing for start of line followed by a negative look ahead to avoid addresses starting with a .: ^(?!\.), and ended with a test for end of line ($).
See some samples here at regex101.
This is what I did and it's fast and works perfectly:
function isIPv4Address(inputString) {
let regex = new RegExp(/^(([0-9]{1,3}\.){3}[0-9]{1,3})$/);
if(regex.test(inputString)){
let arInput = inputString.split(".")
for(let i of arInput){
if(i.length > 1 && i.charAt(0) === '0')
return false;
else{
if(parseInt(i) < 0 || parseInt(i) >=256)
return false;
}
}
}
else
return false;
return true;
}
Explanation: First, with the regex check that the IP format is correct. Although, the regex won't check any value ranges.
I mean, if you can use Javascript to manage regex, why not use it?. So, instead of using a crazy regex, use Regex only for checking that the format is fine and then check that each value in the octet is in the correct value range (0 to 255). Hope this helps anybody else. Peace.
And instead of
{1-3}
you should put
{1,3}
\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b
matches 0.0.0.0 through 999.999.999.999
use if you know the seachdata does not contain invalid IP addresses
\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b
use to match IP numbers with accurracy - each of the 4 numbers is stored into it's own capturing group, so you can access them later
it is maybe better:
function checkIP(ip) {
var x = ip.split("."), x1, x2, x3, x4;
if (x.length == 4) {
x1 = parseInt(x[0], 10);
x2 = parseInt(x[1], 10);
x3 = parseInt(x[2], 10);
x4 = parseInt(x[3], 10);
if (isNaN(x1) || isNaN(x2) || isNaN(x3) || isNaN(x4)) {
return false;
}
if ((x1 >= 0 && x1 <= 255) && (x2 >= 0 && x2 <= 255) && (x3 >= 0 && x3 <= 255) && (x4 >= 0 && x4 <= 255)) {
return true;
}
}
return false;
}
The answers over allow leading zeros in Ip address, and that it is not correct.
For example ("123.045.067.089"should return false).
The correct way to do it like that.
function isValidIP(ipaddress) {
if (/^(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)\.(25[0-5]|2[0-4][0-9]|[1]?[1-9][1-9]?)$/.test(ipaddress)) {
return (true)
}
return (false) }
This function will not allow zero to lead IP addresses.
Always looking for variations, seemed to be a repetitive task so how about using forEach!
function checkIP(ip) {
//assume IP is valid to start, once false is found, always false
var test = true;
//uses forEach method to test each block of IPv4 address
ip.split('.').forEach(validateIP4);
if (!test)
alert("Invalid IP4 format\n"+ip)
else
alert("IP4 format correct\n"+ip);
function validateIP4(num, index, arr) {
//returns NaN if not an Int
item = parseInt(num, 10);
//test validates Int, 0-255 range and 4 bytes of address
// && test; at end required because this function called for each block
test = !isNaN(item) && !isNaN(num) && item >=0 && item < 256 && arr.length==4 && test;
}
}
In addition to a solution without regex:
const checkValidIpv4 = (entry) => {
const mainPipeline = [
block => !isNaN(parseInt(block, 10)),
block => parseInt(block,10) >= 0,
block => parseInt(block,10) <= 255,
block => String(block).length === 1
|| String(block).length > 1
&& String(block)[0] !== '0',
];
const blocks = entry.split(".");
if(blocks.length === 4
&& !blocks.every(block => parseInt(block, 10) === 0)) {
return blocks.every(block =>
mainPipeline.every(ckeck => ckeck(block) )
);
}
return false;
}
console.log(checkValidIpv4('0.0.0.0')); //false
console.log(checkValidIpv4('0.0.0.1')); //true
console.log(checkValidIpv4('0.01.001.0')); //false
console.log(checkValidIpv4('8.0.8.0')); //true
This should work:
function isValidIP(str) {
const arr = str.split(".").filter((el) => {
return !/^0.|\D/g.test(el);
});
return arr.filter((el) => el.length && el >= 0 && el <= 255).length === 4;
}
well I try this, I considered cases and how the entries had to be:
function isValidIP(str) {
let cong= /^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/
return cong.test(str);}
A less stringent when testing the type not the validity. For example when sorting columns use this check to see which sort to use.
export const isIpAddress = (ipAddress) =>
/^((\d){1,3}\.){3}(\d){1,3}$/.test(ipAddress)
When checking for validity use this test. An even more stringent test checking that the IP 8-bit numbers are in the range 0-255:
export const isValidIpAddress = (ipAddress) =>
/^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipAddress)

parseInt() returning incorrect value; DOB validation

Wondering if anyone could shed some light as I’m pulling my hair out over this one!
I have written a simple function to validate a users Date of birth which is all well and good, or at least it was until I realised it wasn't working as expected!
The function, as below, takes 2 parameters, dobNum (the value of an input field) and dmy (a switch variable that receives either ‘dd’, ‘mm’ or ‘yyyy’). The function is called as follows with the value of an input field so there shouldn’t be any object based problems:
onblur=”validateDOB(this.value, ‘mm’);
I have spent ages trying to get to the bottom of this and there seems to be a problem with the parseInt() statement.
This works fine for the days and months until you pass either a 08 (zero, eight) or a 09 (zero,nine). Here the result of the parseInt() returns as 0 rather than an 8 or 9 respectively.
But this is only a problem with 08 and 09, passing numbers 01 to 07 returns 1 to 7 as expected.
Similarly, when passing single digits, 1 to 9, to the function, parseInt() returns the appropriate value as an integer.
Really struggling to fathom this one out. Conversely removing the parseInt statement completely seems to work however this leaves the dobNum value as a string which I don’t feel is particularly good practice.
Can anyone shed some light on this please? (this problem occurs in both firefox and IE)
Many thanks,
SMc
var DOBddOK = false;
var DOBmmOK = false;
var DOByyyyOK = false;
function validateDOB (dobNum, dmy) {
// Set Regexp based on dmy var.
if (dmy.length == 2) var reg = /^([0-9]{1,2})$/;
else var reg = /^([0-9]{4})$/;
var numOK = reg.test(dobNum);
alert("NumOK: "+numOK); //test
// If dobNum value passes regExp test then convert it to an integer
if (numOK) {
var numVar = parseInt(dobNum);
//var numVar = dobNum;
alert("NumVar: "+numVar); //test
}
alert("dmy: "+dmy); //test
switch (dmy) {
case "dd":
if (numOK && numVar <= 31 && numVar > 0) DOBddOK = true;
else DOBddOK = false;
break;
case "mm":
if (numOK && numVar <= 12 && numVar > 0) DOBmmOK = true;
else DOBmmOK = false;
break;
case "yyyy":
var d = new Date();
d = d.getFullYear();
if (numOK && numVar <= (d-18) && numVar >= (d-80)) DOByyyyOK = true;
else DOByyyyOK = false;
break;
}
}
When the parseInt function finds a leading zero in the passed string, it will implicitly parse the number as octal.
It is always recommended to use the radix argument:
parseInt('08', 10); // 8
parseInt('09', 10); // 9
This have caused so many problems over the time that in the new version of the language standard, ECMAScript 5, the implicit octal detection has been removed from the parseInt algorithm. But ES5 is not completely supported yet.
There are other ways to convert a String to Number in JavaScript that do not present this problem, for example:
The unary plus operator:
+'08'; // 8
The Number constructor called as a Function:
Number('08'); // 8
In my opinion parseInt and the later two ways I've described have a (subtly) different semantic meaning.
The former is clearly parsing, for example:
parseInt('12px'); // 12
parseInt('10yo'); // 10
parseInt('1111', 2); // 15
And the last two ways are for doing String to Number type conversion.
It's treating strings with a leading zero as octal, you can specify a second parameter giving the radix as 10.
See link text
Try to use the radix parseInt(dobNum, 10) to parse your integer in base 10

Categories

Resources