SpaceNinja
SpaceNinja

Reputation: 512

Dynamic AngularJS validation that matches an IP address, but where the last octet is within a specific range

In our app, the DHCP Scope comes in with the data. Let's say it's 5.5.5.5. A user can enter an IP Address in this area of the app, but the IP they enter must be the same as the DHCP Scope except that the last octet can be different, and it must be between 2 and 254.

So for the DHCP Scope above, the user can enter an IP between 5.5.5.2 and 5.5.5.254.

I have created a JSFiddle that has everything except the ng-pattern I will need, that's what I need help with: https://jsfiddle.net/spaceninja/6yz09y61/

I think what I need is a RegEx pattern that takes the original IP address and uses it as a pattern except that the last octet must be within a range of 2-254, something like:

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

Except that the [5]s up there would be from the octets in the data, the original 5.5.5.5, but it could be any valid IP that comes in from the data. (and I know the [2-254] is not correct in the above example but I'm still learning RegEx). So it would look maybe like this?

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];

Then, if you could somehow use variables in RegEx, the pattern could be:

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

I don't think you can use variables like that but I hope it explains what I need.

Upvotes: 0

Views: 152

Answers (2)

CognitiveDesire
CognitiveDesire

Reputation: 784

Here is your solution

Let me know if you need any changes

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

    $scope.dhcp = "192.168.1.1"; // This will come in from the data


    $scope.regex = "^(" +$scope.dhcp.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/5/

Upvotes: 1

Joshua J Wilborn
Joshua J Wilborn

Reputation: 526

You can simply create a new regex using the sections from the original IP.

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

Then you can store that regex on the scope to use ng-pattern!

Upvotes: 1

Related Questions