Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
266 views
in Technique[技术] by (71.8m points)

javascript - How to validate an IP in a text field AngularJS

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use:

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...