How to check IP address in AngularJS text box

How to check IP address in text box in AngularJS? I am currently using this code, but it does not work 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]))$/

+4
source share
1 answer

Using:

/\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/

Corresponds to 0.0.0.0 by 255.255.255.255

If you want to abandon 0.0.0.0and 255.255.255.255, I suggest adding an additional operator if. Otherwise, the regular expression will be too complicated.

Example with an observer:

$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

[change]

It is best to create a directive, for example: <ip-input>

In this example, it might be useful to create a directive for user input: format-input-value-in-angularjs

+9

All Articles