如何在文本字段 AngularJS 中验证 IP [英] How to validate an IP in a text field AngularJS
问题描述
如何在 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]))$/
使用:
/\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
我建议你添加额外的 if
语句.否则正则表达式会太复杂.
观察者示例:
$scope.ip = '1.2.3.4';$scope.$watch(function () {返回 $scope.ip;},函数(新值,旧值){如果 (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/)){//匹配尝试成功} 别的 {//匹配尝试失败}})
<小时>
演示 小提琴>
最好的办法是创建指令,例如:
这个例子可能有助于如何为自定义输入创建指令:format-input-value-in-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]))$/
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
这篇关于如何在文本字段 AngularJS 中验证 IP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!