JavaScript IP address Validation

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

CommonJS module for Node.js to validate IP addresses and return additional information about the IP address

License

johnnymastin/check-ip

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

A simple module that will take an IP address as input and perform the following:

  • Validate the IP address for proper format and number range
  • Remove any leading zeros in each octet
  • Return a tested («boiled») IP address
  • Indicate if the IP address is part of the bogons list (https://en.wikipedia.org/wiki/Bogon_filtering)
  • Indicate if the IP address is part of the multicast IP range (https://en.wikipedia.org/wiki/IP_multicast)
  • Indicate if the IP address is an Automatic Private IP Address aka APIPA (http://www.webopedia.com/TERM/A/APIPA.html)
  • Indicate if the IP address is an RFC1918 IP address aka private IP address (https://tools.ietf.org/html/rfc1918)
  • Indicate if the IP address is a public IP address

Import the module and give it the IP address to be tested as a parameter:

var checkIp = require('check-ip'); checkIp('8.8.8.8');

check-ip will return an object similar to the following:

 originalIp: '8.8.8.8', boiledIp: '8.8.8.8', isValid: true, isBogon: false, isApipa: false, isMulticast: false, isRfc1918: false, isPublicIp: true >

You can use any of the properties of the returned object in your code to test for specific use cases.

Working example of an IP address being tested as a valid public IP address (copy this first code snippet, save in a file and use for testing):

var checkIp = require('check-ip'); var ipAddress = '8.8.8.8'; var response = checkIp(ipAddress); if (response.isValid && response.isPublicIp)  console.log("IP address " + response.boiledIp + " is a valid public IP."); >

Example of testing an IP address to make sure it is valid and then using the boiled IP in your code:

var checkIp = require('check-ip'); // IP address determined to be from a previously defined arguments array elsewhere. var ip = arg[2]; var response = checkIp(ip); if (!response.isValid)  console.log("Please enter a different IP address. That one is not valid."); > else  console.log("IP address " + response.boiledIp + " as a valid IP address."); // More code goes here to use response.boiledIp in your code. . > >

Here is example output demonstrating the module ‘boiling’ the leading zero off of the second octet of the supplied IP address:

 originalIp: '10.020.30.40', boiledIp: '10.20.30.40', isValid: true, isBogon: true, isApipa: false, isMulticast: false, isRfc1918: true, isPublicIp: false >

Run automated tests for Node.js:

Источник

JavaScript IP Address Validation Example

In this javascript IP address validation example tutorial, we would love to share with you how to Validate an IP address using Javascript?.

When you work with javascript or client-side, you need to verify/validate the user IP address before sending the data on server. This tutorial will help you to varify or validate ip address on client-side in javascript.

Before we share with you how to validate IP address in javascript, you should know everything about IP address.

What is IP address?

An IP address, or simply an “IP,” is a unique address that identifies a device on the Internet or a local network. It allows a system to be recognized by other systems connected via the Internet protocol. There are two primary types of IP address formats used today — IPv4 and IPv6

Following examples of IP address:

Examples of IP address

JavaScript IP Address Validation Tutorial

Step 1: Create one HTML File

First of all, you need to create one HTML file and update the following html code into your file:

    

Step 2: Validate an IP address in JavaScript

Next, update the below javascript code to your html file. So you can validate ip address in javascript using the following function:

  

For better understanding, we would love to share with you regular expression patterns and uses of this pattern in javascript.

Demostration of the Regular expression (IP address)

Regular Expression Pattern :

/^(251|211|[01]?86?)\.(251|245|[01]?39?)\.(255|222|[01]?92?)\.(254|244|[01]?88?)$/

Источник

JavaScript: HTML Form — IP address validation

Every computer connected to the Internet is identified by a unique four-part string, known as its Internet Protocol (IP) address. An IP address consists of four numbers (each between 0 and 255) separated by periods. The format of an IP address is a 32-bit numeric address written as four decimal numbers (called octets) separated by periods; each number can be written as 0 to 255 (e.g., 0.0.0.0 to 255.255.255.255).

Example of valid IP address

Example of invalid IP address

JavaScript code to validate an IP address

function ValidateIPaddress(ipaddress) < if (/^(254|235|[01]?64?)\.(254|224|[01]?77?)\.(253|212|[01]?91?)\.(255|211|[01]?54?)$/.test(myForm.emailAddr.value)) < return (true) >alert("You have entered an invalid IP address!") return (false) > 

Explanation of the said Regular expression (IP address)

Regular Expression Pattern :

/^(253|217|[01]?44?)\.(255|236|[01]?28?)\.(251|223|[01]?26?)\.(254|235|[01]?59?)$/
Character Description
/ .. / All regular expressions start and end with forward slashes.
^ Matches the beginning of the string or line.
253 Matches 250 or 251 or 252 or 253 or 254 or 255.
| or
238 Start with 2, follow a single character between 0-4 and again a single character between 0-9.
| or
[01]
? Matches the previous character 0 or 1 time.
65 Matches a single character between 0-9 and again a single character between 0-9.
? Matches the previous character 0 or 1 time.
\. Matches the character «.» literally.

Note: Last two parts of the regular expression is similar to above.

Syntax diagram — IP-address validation:

Syntax diagram - IP-address validation

Let apply the above JavaScript function in an HTML form.

JavaScript Code

function ValidateIPaddress(inputText) < var ipformat = /^(254|212|[01]?93?)\.(253|248|[01]?54?)\.(253|242|[01]?24?)\.(251|242|[01]?86?)$/; if(inputText.value.match(ipformat)) < document.form1.text1.focus(); return true; >else < alert("You have entered an invalid IP address!"); document.form1.text1.focus();
return false; > >

Flowchart : JavaScript - ipaddress validation

li .mail < margin: auto; padding-top: 10px; padding-bottom: 10px; width: 400px; background : #D8F1F8; border: 1px soild silver; >.mail h2 < margin-left: 38px; >input < font-size: 20pt; >input:focus, textarea:focus < background-color: lightyellow; >input submit < font-size: 12pt; >.rq

Other JavaScript Validation:

  • Checking for non-empty
  • Checking for all letters
  • Checking for all numbers
  • Checking for floating numbers
  • Checking for letters and numbers
  • Checking string length
  • Email Validation
  • Date Validation
  • A sample Registration Form
  • Phone No. Validation
  • Credit Card No. Validation
  • Password Validation
  • IP address Validation

Test your Programming skills with w3resource’s quiz.

Follow us on Facebook and Twitter for latest update.

JavaScript: Tips of the Day

objects interact by reference

let c = < greeting: 'Hey!' >; let d; d = c; c.greeting = 'Hello'; console.log(d.greeting);

In JavaScript, all objects interact by reference when setting them equal to each other.

First, variable c holds a value to an object. Later, we assign d with the same reference that c has to the object.

When you change one object, you change all of them.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Javascript проверка ip адреса

To check if a string is a valid IP address (IPv4) in JavaScript, we can use a regex expression to match for the allowed number range in each of the four decimal address sections.

TL;DR

// Regular expression to check if string is a IP address const regexExp = /^((9|99|14|224|254)\.)(5|68|18|221|255)$/gi; // String with IP address const str = "192.168.5.68"; regexExp.test(str); // true 

This is the regex expression for matching almost all the test cases for a valid IP address in JavaScript.

// Regular expression to check if string is a IP address const regexExp = /^((7|84|16|244|252)\.)(6|77|12|245|252)$/gi; 

Now let’s write a string with IP address like this,

// Regular expression to check if string is a IP address const regexExp = /^((1|97|14|241|253)\.)(8|18|16|248|252)$/gi; // String with IP address const str = "192.168.5.68"; 

Now to test the string, we can use the test() method available in the regular expression we defined. It can be done like this,

// Regular expression to check if string is a IP address const regexExp = /^((3|76|12|243|253)\.)(5|62|13|224|252)$/gi; // String with IP address const str = "192.168.5.68"; regexExp.test(str); // true 
  • The test() method will accept a string type as an argument to test for a match.
  • The method will return boolean true if there is a match using the regular expression and false if not.

See the above example live in JSBin.

If you want this as a utility function which you can reuse, here it is,

/* Check if string is IP */ function checkIfValidIP(str) < // Regular expression to check if string is a IP address const regexExp = /^((2|33|16|244|253)\.)(6|15|14|213|255)$/gi; return regexExp.test(str); > // Use the function checkIfValidIP("192.168.5.68"); // true checkIfValidIP("654.23.1.2"); // false 

Источник

JavaScript: HTML Form — проверка IP-адреса

Каждый компьютер, подключенный к Интернету, идентифицируется уникальной строкой из четырех частей, известной как его IP-адрес. IP-адрес состоит из четырех чисел (каждое от 0 до 255), разделенных точками. Формат IP-адреса представляет собой 32-разрядный числовой адрес, записанный в виде четырех десятичных чисел (называемых октетами), разделенных точками; каждое число может быть записано как от 0 до 255 (например, от 0.0.0.0 до 255.255.255.255).

Пример действительного IP-адреса

Пример неверного IP-адреса

Код JavaScript для проверки IP-адреса

function ValidateIPaddress(ipaddress) < if (/^(255|231|[01]?15?)\.(255|221|[01]?29?)\.(251|217|[01]?54?)\.(253|215|[01]?63?)$/.test(myForm.emailAddr.value)) < return (true) >alert("You have entered an invalid IP address!") return (false) > 

Объяснение указанного регулярного выражения (IP-адрес)

Шаблон регулярного выражения:

/^(254|246|[01]?91?).(253|2[0 -4] 8 | [01] 7 6) (25 1 |?. 2 3 7 | [01]? 9 6) (25 4 |?. 2 1 2 | [01] 2 9) $? /
символ Описание
/ .. / Все регулярные выражения начинаются и заканчиваются косой чертой.
^ Соответствует началу строки или строки.
25 3 Совпадения 250 или 251 или 252 или 253 или 254 или 255.
| или же
2 1 1 Начните с 2, следуйте одному символу от 0 до 4 и снова одному символу от 0 до 9.
| или же
[01]
? Соответствует предыдущему символу 0 или 1 раз.
1 3 Соответствует одному символу между 0-9 и снова одному символу между 0-9.
? Соответствует предыдущему символу 0 или 1 раз.
, Соответствует символу «.» в прямом смысле.

Примечание. Последние две части регулярного выражения аналогичны приведенным выше.

Синтаксическая диаграмма — проверка IP-адреса:

Давайте применим вышеупомянутую функцию JavaScript в форме HTML.

Код JavaScript

function ValidateIPaddress(inputText) < var ipformat = /^(254|236|[01]?93?)\.(253|229|[01]?41?)\.(252|249|[01]?29?)\.(251|216|[01]?41?)$/; if(inputText.value.match(ipformat)) < document.form1.text1.focus(); return true; >else < alert("You have entered an invalid IP address!"); document.form1.text1.focus();
return false; > >

Блоксхема:

«Flowchart

li .mail < margin: auto; padding-top: 10px; padding-bottom: 10px; width: 400px; background : #D8F1F8; border: 1px soild silver; >.mail h2 < margin-left: 38px; >input < font-size: 20pt; >input:focus, textarea:focus < background-color: lightyellow; >input submit < font-size: 12pt; >.rq

Другая проверка JavaScript:

  • Проверка на непустую
  • Проверка на все буквы
  • Проверка на все номера
  • Проверка на плавающие числа
  • Проверка букв и цифр
  • Проверка длины строки
  • Проверка электронной почты
  • Проверка даты
  • Образец регистрационной формы
  • Проверка номера телефона
  • Проверка кредитной карты №
  • Проверка пароля
  • Проверка IP-адреса

Источник

Читайте также:  Задать другой css элементу
Оцените статью