How to validate an IP in a text field AngularJS

13,504

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

Share:
13,504

Related videos on Youtube

Harikrishnan
Author by

Harikrishnan

I am a full-stack web developer and solutions consultant. Currently working as an Associate Principal Engineer at QBurst. Active member of GDG. Rest of the time I dedicated to opensource projects and Stackoverflow. Openstack foundation member. If you would like to contact me, email me at harikrishnan.vkm186atgmail.com and This is my LinkedIn Profile.

Updated on September 21, 2022

Comments

  • Harikrishnan
    Harikrishnan less than a minute

    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]))$/

  • Ronald91
    Ronald91 about 8 years
    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.
  • Maxim Shoustin
    Maxim Shoustin about 8 years
    @Ronald91 Well, for sure directive way is more appropriate, something like <input-ip>. But SO asks the regex validation. I added watcher only for demo. BTW, this is an example I wrote once with $parsers: stackoverflow.com/questions/19890364/…