4

How to validate an IP in a textfield in AngularJS ? Currently I am using this code, but its not working in all cases . Any idea ?

ng-pattern='/^((([01]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))[.]){3}(([0-1]?[0-9]{1,2})|(2[0-4][0-9])|(25[0-5]))$/

Harikrishnan
  • 9,688
  • 11
  • 84
  • 127

2 Answers2

10

Use:

/\b(?:(?: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]?)\b/

Matches 0.0.0.0 through 255.255.255.255

If you want to drop 0.0.0.0 and255.255.255.255 I suggest you to add additional if statement. Otherwise the regex will be too complicated.

Example with watcher:

$scope.ip = '1.2.3.4';

    $scope.$watch(function () {
        return $scope.ip;
    },

    function (newVal, oldVal) {            
        if (
            newVal != '0.0.0.0' && newVal != '255.255.255.255' &&
            newVal.match(/\b(?:(?: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]?)\b/))
        {
             // Match attempt succeeded
        } else {
            // Match attempt failed
        }
    })

Demo Fiddle

[Edit]

The best bet is to create directive, something like: <ip-input>

This example might helpful how to create directive for custom input: format-input-value-in-angularjs

Community
  • 1
  • 1
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
  • Instead of adding a watch in your controller you can put this functionality inside an angular function and use that as an expression in the ng-change directive. – Ronald91 Aug 28 '14 at 13:20
  • @Ronald91 Well, for sure directive way is more appropriate, something like ``. But SO asks the regex validation. I added watcher only for demo. BTW, this is an example I wrote once with `$parsers`: http://stackoverflow.com/questions/19890364/format-input-value-in-angularjs/19890485#19890485 – Maxim Shoustin Aug 28 '14 at 13:27
0

Here's a directive to validate IPv4 and IPv6 address

app.directive('ipformat',function(){
  return {
      require: 'ngModel',
      link: function(scope,elem,attrs,ctrl){
          ctrl.$validators.ipformat= function (modelValue){
              if (ctrl.$isEmpty(modelValue)){
                  return false;
              }
              var expression = /((^\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0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))/;
              if (expression.test(modelValue)) {
                return true;
            }
            else {
              return false;
            }
          }
      }
  }
});

And use this directive with input field in forms as

<input type="text" class="form-control" name="ipaddresstxt" id="ipaddressid"
                                     ng-model="ipaddress" 
                                     ipformat>

Remember directive requires ng-model. Feel free to update as per usage.