time limit on regular expression in format MM:SS:HH - javascript

I need to validate a user input for minutes, seconds, and hundredths in the format MM:SS:HH. However, user's input can not go over 10 minutes. I'm not sure how to limit that and still keep for example 01:01:01 valid.
/^[0-1][0-0]:[0-5][0-9]:[0-9][0-9]$/
This is the expression I had, but my example of 01:01:01 would not have worked.

Brief
I would definitely split the time string on : and then test each part. That's the simplest solution. Alternatively, you can do this relatively easily using regex.
Code
Method 1 - No regex
const str = ["00:00:00", "05:05:05", "10:00:00", "10:00:01", "10:59:59", "20:20:20"];
str.forEach(function(s) {
var a = s.split(":").map(Number);
if(a[0] < 10 || (a[0] === 10 && a[1] === 0 && a[2] === 0)) {
console.log(`Valid: ${s}`);
} else {
console.log(`Invalid: ${s}`);
}
});
Method 2 - Regex
const regex = /^(?:0\d(?::[0-5]\d){2}|10:00:00)$/;
const str = ["00:00:00", "05:05:05", "10:00:00", "10:00:01", "10:59:59", "20:20:20"];
str.forEach(function(s) {
if(regex.exec(s) !== null) {
console.log(`Valid: ${s}`);
} else {
console.log(`Invalid: ${s}`);
}
});
Explanation
I'll only explain the regex in Method 2 as the rest is fairly simple. If you need an explanation about any other parts, however, feel free to ask!
^ Assert position at the start of the line
(?:0\d(?::[0-5]\d){2}|10:00:00) Match either of the following
0\d(?::[0-5]\d){2} Match the following
0 Match this literally
\d Match any digit
(?::[0-5]\d){2} Match the following exactly twice
: Match this literally
[0-5] Match a number in the range between 0 and 5
\d Match any digit
10:00:00 Match this literally
$ Assert position at the end of the line

/(10:00:00|^0[0-9]:[0-5][0-9]:[0-5][0-9]$)/
['10:00:01', '10:00:00', '09:59:59', '05:05:05']
.forEach(t => console.log(t.match(/(10:00:00|^0[0-9]:[0-5][0-9]:[0-5][0-9]$)/)))

Your regex is close. Simply change your regex to:
/^(10:00:00|0[0-9]:[0-5][0-9]:[0-9][0-9])$/

Related

JavaScript regex two string number separated by ( : ) individual max min calculation

I need to validate JavaScript string like "03:39" with Regex. Rules are following,
1.First part of the string which is before (:) is allowed from 0 to 24
2.Second part of the string which is after (:) is allowed from 0 to 59
3.Single digit number of both part can either be start with 0 like 01 or 02 or with out 0 like 1 , 2.
Now i have wrote a JavaScript regex code which is following.
var dateRegEx = /^n(0[0-2][0-4]|[0-24])(:)(0|[0-5][0-9]|[0-59])$/;
if ($(element).val().match(dateRegEx) === null) {
// my rest of the code
}
now, when user insert 0:38, 01:38 or 02:59 it get validated but when the first part incensed after 2 like 03:38 it not validating the string.
So what am i doing wrong ??
For hours, your current 0[0-2][0-4] requires three digits (none of which can be above 4), whereas [0-24] will only match one digit (a 0, 1, 2, or 4).
Rather, to match hours (00 to 24), you should use (?:2[0-4]|[01]?[0-9]); either a 2 followed by a number from 0 to 4, or an (optional) 0 or 1 followed by any other digit.
To match minutes (00 to 59), use [0-5]?[0-9] - an optional digit from 0 to 5, followed by a digit from 0 to 9.
^(?:2[0-4]|[01]?[0-9]):[0-5]?[0-9]$
https://regex101.com/r/0QxX7w/1
Note that if you're just matching a single character like :, don't put it in a character set. Also, because you don't want an n at the beginning of the match, remove it from the beginning of your pattern.
Well i think you don't need regex here you can do directly like this
function check(input){
let temp = input.split(':')
return (0 <= temp[0] && temp[0] <=24 ) && ( 0<= temp[1] && temp[1] <=59)
}
console.log(check('03:380'))
console.log(check('03:38'))
console.log(check('30:0'))
With regex you can do it like this
function check(input){
return /^(?:[01]?[0-9]|[0-2][0-4]):[0-5]?[0-9]$/.test(input)
}
console.log(check('03:30'))
console.log(check('03:380'))
console.log(check('33:30'))
console.log(check('24:59'))
console.log(check('03:60'))
console.log(check('0:0'))
console.log(check('0:30'))

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 RegExp to automatically format Pattern

I have seen a lot of functions that format telephone or number (comma and decimals) in stackflow community like this question here and others. Here's what I want to:
Step 1: Maintain a Library for patterns like this:
var library = {
fullDate : {
pattern : /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/,
error : "Invalid Date format. Use YYYY-MM-DD format."
},
fullDateTime : {
pattern : /^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2} [0-9]{1,2}:[0-9]{1,2}$/,
error : "Invalid DateTime format. Use YYYY-MM-DD HH:MM (24-hour) format."
},
tel : {
pattern : /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error : "Invalid Telephone format."
}
};
Step 2: Automatically add a character as they type. For exapmple, add a - after 4 numbers in Date.
I have a text field say:
<input type="text" data-validate="fullDate" placeholder="YYYY-MM-DD"/>
And possible place to start script as:
$('body').on('keyup','input',function(){
var validate = $(this).data('validate');
var pattern = library[validate].pattern;
//Some more steps here....
});
But, I cannot make any further because I am new to RegExp. Here's a startup fiddle. Anyone?
Further Notes: I have been able to validate using the following functions but what I want to is automatically make pattern:
function validate(libraryItem, subject){
var item = library[libraryItem];
if(item !== undefined){
var pattern = item.pattern;
if(validatePattern(pattern, subject)){
return true;
} else {
return item.error;
}
}
return false;
}
function validatePattern(pattern, subject){
return pattern.test(subject);
}
It is not as complicated as you think. What you are looking for is JQuery Masked input and other alternative libraries. Here is the documentation. All you need is:
<input id="date" type="text" placeholder="YYYY-MM-DD"/>
and the script:
$("#date").mask("9999-99-99",{placeholder:"YYYY-MM-DD"});
Here is demo pen link:
http://codepen.io/anon/pen/gpRyBp
To implement validation use this library:
https://github.com/RobinHerbots/jquery.inputmask
What needed here is breaking up the regular expression in sub expression which matches part of the string and suggest completion based upon next character in the Regular Expression.
I wrote a naive Parser which parses the expression and divides into atomic subexpression.
var parser = function(input) {
var tokenStack = [];
var suggestions = [];
var suggestion;
var lookAhead;
if (input[0] === '/')
input = input.slice(1, input.length - 1);
var i;
for (i = 0; i < input.length - 1; i++) {
lookAhead = input[i + 1];
switch (input[i]) {
case '(':
tokenStack.push('(');
break;
case '[':
tokenStack.push('[');
break;
case ')':
if (tokenStack[tokenStack.length - 1] === '(') {
tokenStack.pop();
if (tokenStack.length === 0) {
suggestion = generateSuggestion(input, i);
if (suggestion !== null)
suggestions.push(suggestion);
}
}
else
throw 'bracket mismatch';
break;
case ']':
if (lookAhead === '{') {
while (input[i] !== '}')
i++;
}
if (tokenStack[tokenStack.length - 1] === '[') {
tokenStack.pop();
if (tokenStack.length === 0) {
suggestion = generateSuggestion(input, i);
if (suggestion !== null)
suggestions.push(suggestion);
}
}
else
throw 'bracket mismatch';
break;
default:
if (tokenStack.length === 0) {
suggestion = generateSuggestion(input, i);
if (suggestion !== null)
suggestions.push(suggestion);
}
break;
}
}
return suggestions;
}
var generateSuggestion = function(input, index) {
if (input[index].match(/[a-zA-Z\-\ \.:]/) !== null)
return {
'regex': input.slice(0, index) + '$',
'suggestion': input[index]
};
else
return null;
}
Here is sample input and output of parser()
parser('/^[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}$/');
// output:
[ { regex: '^[0-9]{4}$', suggestion: '-' },
{ regex: '^[0-9]{4}-[0-9]{1,2}$', suggestion: '-' } ]
Thus on every keyup you need to check the list of RegExp generated by parser and if any of it matches the input then use the suggestion.
EDIT:
Edited generateSuggestion to match only full expression.
Here is sample fiddle: http://jsfiddle.net/a7kkL6xu/6/
With backspace ignored: http://jsfiddle.net/a7kkL6xu/7/
This could be done with a single regex.
This requires a MM:DD and HH:MM to be 2 digits and YYYY to be 4 digits on a
fully valid entry, but matches all the partials.
It could be made to allow a single digit validity for the 2 digit valid mentioned.
But doing so, will make premature suggestions on the - - [ ] : form.
If you want to not inject the suggestion, then 1 or 2 digits is fine.
JavaScript doesn't allow lookbehind assertions, so partial field expressions
are below the valid field expressions in their respective groups.
Basically what happens is the input is rewritten on each key press event.
All you do is match the current input within the event handler.
Without suggestions, you just write over the input with the entire match (group 0).
The match (group 0) will only contain a valid partial or full match.
The valid completed field capture groups are 1 through 5
[ Year, Month, Day, Hours, Minutes ]
The incomplete field captures are groups 6 through 10
[ Minutes, Hours, Day, Month, Year ]
This is the logic:
// Note 1 - can handle control chars by just returning.
// Note 2 - can avoid rewrite by keeping a global of last good,
// then return if current == last.
if ( last char of group 0 is a dash '-' or space ' ' or colon ':'
or any of groups 6 - 10 matched
or group 5 matched )
set input equal to the group 0 string;
else if ( group 4 matched ) // Hours
set input equal to group 0 string + ':';
else if ( group 3 matched ) // Day
set input equal to group 0 string + ' ';
else if ( group 1 or 2 matched ) // Year or Month
set input equal to group 0 string + '-';
else // Here, effectively strips bad chars from input box
// before they are displayed.
set input equal to group 0 string;
Note that if a group didn't match it's value will be NULL
and to check the entire validity, there should be no partials and
groups 1 - 3 must be complete for just YYYY-MM-DD or 1 - 5 with the optional
time HH:MM
Final Note: This is a parser, and effectively a test case of the look and feel, ie. flicker, of real time input rewrite.
If it goes well, the logic in the handler can include Day validation (and rewrite) based on the month.
Also, the premise can be expanded to any type of input, any type of form and
form delimiter combinations, etc..
If it works, you can build a library.
# /^(?:(19\d{2}|20[0-1]\d|202[0-5])(?:-(?:(0[1-9]|1[0-2])(?:-(?:(0[1-9]|[1-2]\d|3[0-1])(?:[ ](?:(0\d|1\d|2[0-3])(?::(?:(0\d|[1-5][0-9])|([0-5]))?)?|([0-2]))?)?|([0-3]))?)?|([01]))?)?|(19\d?|20[0-2]?|[12]))/
^ # BOL
(?:
( # (1 start), Year 1900 - 2025
19 \d{2}
| 20 [0-1] \d
| 202 [0-5]
) # (1 end)
(?:
- # -
(?:
( # (2 start), Month 00 - 12
0 [1-9]
| 1 [0-2]
) # (2 end)
(?:
- # -
(?:
( # (3 start), Day 00 - 31
0 [1-9]
| [1-2] \d
| 3 [0-1]
) # (3 end)
(?:
[ ] # space
(?:
( # (4 start), Hour 00 - 23
0 \d
| 1 \d
| 2 [0-3]
) # (4 end)
(?:
: # :
(?:
( # (5 start), Minutes 00 - 59
0 \d
| [1-5] [0-9]
) # (5 end)
|
( [0-5] ) # (6)
)?
)?
|
( [0-2] ) # (7)
)?
)?
|
( [0-3] ) # (8)
)?
)?
|
( [01] ) # (9)
)?
)?
|
( # (10 start)
19 \d?
|
20 [0-2]?
|
[12]
) # (10 end)
)
It is only possible to add a character if it is the single possible choice at this point. An example would be a regex for the YYYY-MM-DD HH24:mm format: the -, the : and the (space) could be added. Here is the corresponding regex (/ ommitted to make it more readable, it is stricter than the one in the question, some illegal dates are still possible like 31st of February):
^[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[12][0-9]|3[01]) (?:[01][0-9]|2[0-3]):[0-5][0-9]$
For fixed length inputs you could use #DineshDevkota's solution to add the literals and verify the whole text with regex. I think it's the cleanest and simplest solution. You could also capture the year, month and day to verify the day mathematically. Also rules like "date not in the future" or "max. 100 years in past" can only be veryfied in JS and not with just regex.
The only additional patterns that come to mind where a character could be automatically added:
A + after a literal, e.g. on A+ add an A
Minimal occurances in general, e.g. on (?:foo){2,5} add foofoo not to be confused with [fo]{2,5} where no characters can be added
Literals after the max length of a variable part, e.g. on (?:foo){1,3}bar add bar after the text is foofoofoo before it is not possible.
Add remainders e.g. foo|bar add ar when b was typed and oo when f was typed (also possible in the pattern shown in 3.) but this won't work for ^[a-z]+?(?:foo|bar)$ because we don't know when the user plans on ending the text and it can get really complicated (foo|flo|flu|food|fish only sh can be added after fi).
As seen in 3. and 4. those additional cases where characters could be added are of very limited use as soon as there are parts with variable length. You would have to parse the regex, split it in literal and regex parts. Then you have to parse/analyse the regex parts to incorporate the additional cases mentioned above where characters could be added. Really not worth the trouble if you ask me. (Not a single character can be added in your tel pattern.)

Year of date validation is failing

I need to do a date validation to accept it in dd/mm/yyyy format. However all conditions are working fine except that if I enter year of 6 digits it is also accepting it, like -
12/12/200000
as per my code is valid. Below is my code:
function validate(value) {
if(!value.match(/\d\d\/\d\d\/\d\d\d\d/))
return false;
return checkdate(value);
}
function checkdate(val)
{
var dates = val.split(/\D/);
if(dates[0] <= 0 || dates[0] > 31)
return false;
if(dates[1] <= 0 || dates[1] > 12)
return false;
var now = new Date(dates[2],dates[1]-1,dates[0]);
if (isNaN(now))
return false;
now.setHours(0,0,0,0);
if (now.getFullYear() == dates[2] && now.getMonth() + 1 == dates[1] && now.getDate() == dates[0])
return true;
return false;
}
I am not sure why it allowing year as 6 digits valid input?
The problem is in validate function, regular expression it matches against allows input values you don't want to pass as valid. Besides obvious dd/mm/yyyy format, it allows found text to be anywhere in string. Basically, you said for it to check "if there's said expression inside string", when it should have been "if the whole string matches this expression".
To fix the issue, add ^ at the beginning and $ at the end. ^ stands for string start and $ for string end:
/^\d\d\/\d\d\/\d\d\d\d$/
I think you would benefit from reading documentation on regular expression syntax used by JavaScript.
While at at, humans tend to have issues reading long repeating sequences of similar characters, like in your regexp. This expression is easer to understand and does exactly the same thing:
/^\d{2}\/\d{2}\/\d{4}$/
You're not limiting the regex with start and stop delimiters, so 12/12/200000 is a match as it matched the regex, and then some
if (!value.match(/^\d\d\/\d\d\/\d\d\d\d$/) )
As a sidenote, you don't have to type \d four times, you can do \d{4} to match four instances of \d
If you want to validate a date string by creating a Date object, you don't need to check the entire pattern, just create and Date and check the result. Do you really need two digits for day and month number?
If you want a 4 digit year, that must be checked separately as the constructor will happily convert two digit years to 20th century. If you really need two digit day and month, that can be checked at the same time as the year:
function validateDMY(s) {
var b = s.split(/\D/);
var d = new Date(b[2], --b[1], b[0]);
return d && /^\d{4}$/.test(b[2]) && b[1] == d.getMonth();
}
console.log(validateDMY('30/02/2015')); // false
console.log(validateDMY('30/22/2015')); // false
console.log(validateDMY('02/02/15')); // false
console.log(validateDMY('30/01/2015')); // true

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)

Categories

Resources