I understand that if the parseFloat function encounters any character other than numeric characters (0-9+-. and exponents) it just evaluates the number up to that character, discarding anything else.
I'm having a problem where I need to be able to validate numbers with thousand separators like so:
var number = "10,000.01"; //passes
var numberWithoutThousand = "10000.01"; //fails
//i.e:
if(parseFloat(number) <= 10000) {
return true;
}
//passess
problem is the above code returns true when technically that number is larger than 10,000.
What's the best way to get around this? I've considered stripping out the comma before testing the number, but not sure that is a good strategy.
You don't have numbers, you have strings, so just removing the comma is the way to go
number = number.replace(/\,/g, '');
Your "stripping the comma" strategy seems good to me.
if ( parseFloat( number.replace(",","") ) ) { etc(); }
As has been suggested, to have , in the number it must be a string and so do a search and replace. If you are having to do this on a regular basis then make yourself a reusable function.
Javascript
function myParseFloat(value) {
if (typeof value === 'string') {
value = value.replace(/,/g, '');
}
return parseFloat(value);
}
var number1 = "10,000.01",
number2 = "10000.01",
number3 = 10000.01;
console.log(myParseFloat(number1), myParseFloat(number2), myParseFloat(number3));
Output
10000.01 10000.01 10000.01
On jsFiddle
Thanks for your help with my earlier question:
How to find all instances and display in alert
Now I discover that I need to include some invalid character validation.
I'm trying to figure out how to include a set of regex invalid characters as part of the validation that will also show up in the same alert/textbox/whatever as the "too long/too short" validation.
So, I have a textbox which users will type or paste comma separated values such as AAAAAAA,BBBBBBB,CCCCCCCC,DDDDDDDD
And they cannot be more or less than seven characters long and they can only include certain characters.
I currently have have two separate pieces of Javascript that I'm trying to now combine:
var Invalidchars = "1234567890!##$%^&*()+=[]\\\';./{}|\":<>?";
for (var i = 0; i < document.getElementById("TextBox1").value.length; i++) {
if (Invalidchars.indexOf(document.getElementById("TextBox").value.charAt(i)) != -1){
alert
and this
var val = document.getElementById("Textbox1").value,
err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
return true;
Any help is much appreciated!
=================================================
SOLUTION
Took a while, but using Tenub's code (which didn't quite combine my two sets code, but was close enough), I finally figured out how to merge my two sets of code into one. Here's the code if anyone is ever interested in using it:
var val = document.getElementById("TextBox1").value,
err = $.grep(val.split(','), function(a) {return (a.length = (!/^[^0-9!##$%^&*()+=;.\/\{}|:<>\\?\[\]\'\"]{7}$/.test(a)));});
if (err.length){
document.getElementById("DIV1").style.display = "inline-block";
document.getElementById("TextBox2").value = err.join(',');
return callback (false);
}
document.getElementById("DIV1").style.display = "none";
return true;
The answer is as simple as it is elegant:
var val = document.getElementById("Textbox1").value;
if(!/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test(val)) {
// handle invalid value
}
This tests that the string is 7 characters in length and does not contain any character within the brackets after the "^" (also some characters are escaped with a "\").
You can test in console:
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adfFDKZ'); // returns true
/[^0-9!##$%^&*()+=;./{}|:<>?\[\]\\\'\"]{7}/.test('adf(DKZ'); // returns false
Try this:
/*
* This regex matches all the invalid characters. I escaped the
* special characters.
*/
var regex = /.*[0-9!##\$%\^&\*\(\)\+=\[\]\\';\./\{\}\|":\<\>\?]+.*/;
var text = document.getElementById("TextBox1").value;
/* Test for match...much faster than a for-loop under any circumstances */
if (text.matches(regex)) {
alert("Invalid characters present. Please correct the input");
return false;
}
/* split on delimiter */
var err = $.grep(val.split(','), function(a) { return a.length != 7; });
if (err.length) {
alert("All entries must be seven (7) characters in length. Please correct the following entries: \n" + err);
return false;
}
Please tell me if there are any bugs in this. Also, the only real way to test for this in one step is to set up an enormously long regex. Also, with only one check, it would make it a little harder to guide the user to make the right correction. I will mention that.
After doing a sqrt()
How can I be check to see if the result contains only whole numbers or not?
I was thinking Regex to check for a decimal - if it contains a decimal, that means it didn't root evenly into whole numbers. Which would be enough info for me.
but this code isnt working...
result = sqrt(stringContainingANumber);
decimal = new RegExp(".");
document.write(decimal.test(result));
I bet there's other ways to accomplish the same thing though.
. means any char.
You have to quote the dot. "\."
Or you could test
if (result > Math.floor(result)) {
// not an decimal
}
You can use the % operator:
result % 1 === 0; // rest after dividing by 1 should be 0 for whole numbers
Use indexOf():
var myStr = "1.0";
myStr.indexOf("."); // Returns 1
// Other examples
myStr.indexOf("1"); // Returns 0 (meaning that "1" may be found at index 0)
myStr.indexOf("2"); // Returns -1 (meaning can't be found)
"." has meaning in the regex syntax which is "anything" you need to escape it using "\."
If its a string we can just use split function and then check the length of the array returned. If its more than 1 it has decimal point else not :). This doesn't work for numbers though :(. Please see the last edit. It works for string as well now :)
function checkDecimal() {
var str = "202.0";
var res = str.split(".");
alert(res.length >1);
var str1 = "20";
alert(str1.split(".").length>1);
}
Hope it helps someone.
Happy Learning :)
Are you looking for checking string containing decimal digits ,
you can try like this
var num = "123.677";
if (!isNaN(Number(num)) {
alert("decimal no");
}
else {
alert("Not a decimal number");
}
I am sorry. This answer is too late. but I hope this will help.
function isThisDecimal(val){
if (!(val.indexOf(".") == -1)){
return true; // decimal
}
return false; // number
}
console.log(isThisDecimal("12.00")); //true
console.log(isThisDecimal("12.12")); //true
console.log(isThisDecimal("12"));// false
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)
I want to check if a string contains only digits. I used this:
var isANumber = isNaN(theValue) === false;
if (isANumber){
..
}
But realized that it also allows + and -. Basically, I want to make sure an input contains ONLY digits and no other characters. Since +100 and -5 are both numbers, isNaN() is not the right way to go.
Perhaps a regexp is what I need? Any tips?
how about
let isnum = /^\d+$/.test(val);
string.match(/^[0-9]+$/) != null;
String.prototype.isNumber = function(){return /^\d+$/.test(this);}
console.log("123123".isNumber()); // outputs true
console.log("+12".isNumber()); // outputs false
If you want to even support for float values (Dot separated values) then you can use this expression :
var isNumber = /^\d+\.\d+$/.test(value);
Here's another interesting, readable way to check if a string contains only digits.
This method works by splitting the string into an array using the spread operator, and then uses the every() method to test whether all elements (characters) in the array are included in the string of digits '0123456789':
const digits_only = string => [...string].every(c => '0123456789'.includes(c));
console.log(digits_only('123')); // true
console.log(digits_only('+123')); // false
console.log(digits_only('-123')); // false
console.log(digits_only('123.')); // false
console.log(digits_only('.123')); // false
console.log(digits_only('123.0')); // false
console.log(digits_only('0.123')); // false
console.log(digits_only('Hello, world!')); // false
Here is a solution without using regular expressions:
function onlyDigits(s) {
for (let i = s.length - 1; i >= 0; i--) {
const d = s.charCodeAt(i);
if (d < 48 || d > 57) return false
}
return true
}
where 48 and 57 are the char codes for "0" and "9", respectively.
This is what you want
function isANumber(str){
return !/\D/.test(str);
}
in case you need integer and float at same validation
/^\d+\.\d+$|^\d+$/.test(val)
function isNumeric(x) {
return parseFloat(x).toString() === x.toString();
}
Though this will return false on strings with leading or trailing zeroes.
Well, you can use the following regex:
^\d+$
if you want to include float values also you can use the following code
theValue=$('#balanceinput').val();
var isnum1 = /^\d*\.?\d+$/.test(theValue);
var isnum2 = /^\d*\.?\d+$/.test(theValue.split("").reverse().join(""));
alert(isnum1+' '+isnum2);
this will test for only digits and digits separated with '.' the first test will cover values such as 0.1 and 0 but also .1 ,
it will not allow 0. so the solution that I propose is to reverse theValue so .1 will be 1. then the same regular expression will not allow it .
example :
theValue=3.4; //isnum1=true , isnum2=true
theValue=.4; //isnum1=true , isnum2=false
theValue=3.; //isnum1=flase , isnum2=true
Here's a Solution without using regex
const isdigit=(value)=>{
const val=Number(value)?true:false
console.log(val);
return val
}
isdigit("10")//true
isdigit("any String")//false
If you use jQuery:
$.isNumeric('1234'); // true
$.isNumeric('1ab4'); // false
If you want to leave room for . you can try the below regex.
/[^0-9.]/g
c="123".match(/\D/) == null #true
c="a12".match(/\D/) == null #false
If a string contains only digits it will return null