javascript 如何在文本字段 AngularJS 中验证 IP

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25548351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:39:21  来源:igfitidea点击:

How to validate an IP in a text field AngularJS

javascriptangularjsangular-ui

提问by Harikrishnan

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 ?

如何在 AngularJS 的文本字段中验证 IP?目前我正在使用此代码,但并非在所有情况下都有效。任何的想法 ?

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

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

回答by Maxim Shoustin

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

匹配 0.0.0.0 到 255.255.255.255

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

如果你想删除0.0.0.0255.255.255.255我建议你添加额外的if语句。否则正则表达式会太复杂。

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

演示 Fiddle

[Edit]

[编辑]

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

最好的办法是创建指令,例如: <ip-input>

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

这个例子可能有助于如何为自定义输入创建指令: format-input-value-in-angularjs