如何验证的IP,在AngularJS文本字段?目前我使用这个code,但它不是在所有情况下工作。任何想法?
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]))$/
解决方案使用:
/\\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/匹配0.0.0.0通过255.255.255.255
如果您要删除 0.0.0.0
和 255.255.255.255
我建议你添加额外的如果
语句。否则,正则表达式将是太复杂了。
的与守望示例:的
$ scope.ip ='1.2.3.4'; $范围。$表(函数(){ 返回$ scope.ip; }, 功能(的newval,OLDVAL){ 如果( 的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/)) { //匹配尝试成功 }其他{ //匹配尝试失败 } })
演示 小提琴
最好的办法是创造指令,是这样的:< IP输入>
这个例子可能有用如何创建自定义输入指令:format-input-value-in-angularjs
How to validate an IP in a text field in AngularJS ? Currently I'm 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]))$/
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