AngularJS validation that dynamically checks if an IP address is valid, focusing on ensuring that the last octet falls within a specified range

Our app requires users to input an IP Address that falls within the DHCP Scope provided. For example, if the DHCP Scope is 5.5.5.5, users can enter any IP between 5.5.5.2 and 5.5.5.254.

I have set up a JSFiddle with all the necessary elements, but I am facing difficulty creating the ng-pattern for validation: https://jsfiddle.net/spaceninja/6yz09y61/

I believe a RegEx pattern that takes the original IP address as a base and allows for variations in the last octet within the range of 2-254 should work. Something like this:

$scope.regex = /[5][.][5][.][5][.][2-254]/g;

However, I need the RegEx pattern to dynamically adjust based on the initial IP address provided in the data. It should adapt to any valid IP structure received. Here's a sample code snippet:

var originalIP = "192.168.2.3";
var parts = ip.split('.');
var octet1 = parts[0];
var octet2 = parts[1];
var octet3 = parts[2];
var octet4 = parts[3];

If it were possible to incorporate variables in the RegEx pattern, it could potentially look like this:

$scope.regex = /[octet1][.][octet2][.][octet3][.][2-254]/g;

Although using variables directly in RegEx might not be feasible, I hope this clarifies the requirements for the pattern needed.

Answer №1

Here is the solution provided for you

Please feel free to let me know if there are any adjustments needed

let myApp = angular.module('myApp', [])
  .controller('fiddleCtrl', ['$scope', function($scope) {

    $scope.ipAddress = "192.168.1.1"; // This value will be retrieved from the data


    $scope.regexPattern = "^(" +$scope.ipAddress.split('.').slice(0,3).join('.') + "." +")([2-9]|([1-9][0-9])|([1][0-9][0-9])|([2][0-5][0-4]))$";

  }]);

https://jsfiddle.net/6yz09y61/6/

Answer №2

To generate a custom regular expression for the given IP address, simply break it down into its different sections.

var ipAddress = ('5.5.5.5').split('.');
var customRegex = RegExp(ipAddress[0] + '\.' + ipAddress[1] + '\.' + ipAddress[2] + '\.[2-254]')

After creating the regex, you can save it on the scope and utilize ng-pattern as needed!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing jQuery for extracting information from JSON datasets

I've been grappling with getting jQuery to interpret JSON data, but it keeps coming back as undefined. $.post( wce_data.url, { userid : userId, token : accessToken }, 'json') .done(function( data ) { consol ...

Are there any JS/jQuery plugins available for sliding animations that include slideLeft and slideRight functions, similar to the slideUp and slideDown functions?

Does anyone know of a jQuery/JS plugin that combines fading and sliding effects, specifically with slideLeft and slideRight functions similar to jQuery's slideUp and slideDown? I'm hoping to find something ready-made rather than having to build i ...

Step-by-step guide on utilizing filesystem I/O to upload a file in a Mean app

I have encountered an issue while using the fs module to upload a file in my web application. Despite the console showing that the file has been successfully saved to the specified location, the file itself does not appear there. Below is the code snippet ...

Can one manipulate SVG programmatically?

Looking to develop a unique conveyor belt animation that shifts items on the conveyer as you scroll down, then reverses when scrolling up. I discovered an example that's close to what I need, but instead of moving automatically, it should be triggered ...

Guidelines for submitting and displaying content on a single page with jQuery and MySQL

Objective: To develop a Q&A Script using PHP, JavaScript, and jQuery that allows users to post questions and provide answers. Upon submitting a new answer, it should be stored in the database and automatically displayed in the answers section. Challenge: ...

How to eliminate query parameters from the URL in AngularJS?

After entering the URL http://localhost/HTMLUS12706?key=1234 and being redirected to http://localhost/HTMLUS12706/?key=1234#/index, my goal is to eliminate the query parameter ?key=1234 from the URL and update it to http://localhost/HTMLUS12706/#/index. I ...

Obtaining an XML element within an XSLT transformation

I need to retrieve the value of an XML element within XSL. Although my JavaScript is able to select one XML document, there are elements in other documents that I also require. I am uncertain if this task is feasible or if my syntax is incorrect. This is ...

Can an AngularJS end-to-end scenario test access GET parameters?

Utilizing the runner.html E2E test file for integration testing on an Angular project. //Within runner.html <script src="scenarios.js"></script> //Inside scenarios.js, there is some code like this: describe('App', function() { p ...

Dynamic layout of images with varying dimensions

Discovering the explore section on Flickr was quite intriguing for me: I found it impressive how they showcase pictures in various sizes and how the layout adapts when you resize the browser window. [UPDATE] How do you think one could create a similar di ...

Is there a method to bypass the need for app.get() for each static file in express?

As I delve into using express.js, I'm faced with the task of serving numerous static files from my server - whether it's a .css, .jpg, .svg, .js, or any other file type. Is there a way to accomplish this without having to manually use app.get() f ...

Encountering a 400 error while trying to implement file upload feature in Spring AngularJS -

Whenever I attempt to upload a file using Spring and AngularJS, I keep encountering the dreaded 400 Bad Request error: > error: "Bad Request" > exception: "org.springframework.web.multipart.support.MissingServletRequestPartException" > message: " ...

The consistent index is shared among all dynamically generated elements

I'm currently working on a project where I am generating dropdowns within a table dynamically. I am attempting to determine the index of the dropdown that triggered the event in the following way: $(".template").on('change', '.dataType ...

Save the model with the updated value

Currently, I am working on a piece of code that involves the following: <select ng-model="rule.platforms" ng-options="platform for platform in platforms" name="platform" multiple required> <option value="">-- platform --</option& ...

AngularJS: mouse events not being received by multiple directives on one page

Within my Angular application, I have a group of intricate D3 directives that are all included in a single view. Originally, each directive was placed on separate views with various content, and they functioned as expected in that setup. However, it was de ...

JQuery HTML not functioning properly with dynamically inserted elements

Initially, I perform this action var columns = row.getElementsByTagName('td'); columns[2].innerHTML ='<Button class="btn btn-success" style="margin-right:4px;" onclick="savecategory(this.parentNode,this)"> ...

What could be the reason for not receiving any response from my Firestore query?

Hey there! I'm delving into the world of Firebase for the first time and just set up the Firestore emulator. I've added some data that I want to fetch in my Nextjs app. Once I initialized firebase, this is what my component code looks like: funct ...

Encountering difficulties while loading an external CSS file using Node/Express - receiving a 404 error code

Hey there, I need help setting up an Express app with a particular file structure. Here is how it looks: ![my architecture][1] Build Core/pulse.core/assets/styles/global.css app.js Express_app views/home.jade controller/routes.js node_modules Here ...

Struggling to get collapsible feature functioning on website

I'm trying to create a collapsible DIV, and I found a solution on Stack Overflow. However, I'm having trouble getting it to work on my website. I created a fiddle with the full code, and it works there. But when I implement it on my site, the con ...

Transitioning from Backbone to AngularJS - What challenges can be expected?

Currently I am deep into a large Backbone project (around 8000 lines of JavaScript, not counting external libraries) and I am contemplating making the switch to AngularJS. At the moment, a significant portion of my code deals with DOM manipulation, event ...

What is the method to configure Angular to wait for the server to load session information data?

The server holds session information that is utilized in several controllers within my application. Is there a way to have Angular wait until the session has fully loaded during startup? ...