【问题标题】:ng-pattern In Angular JS for IP Address Validation [duplicate]Angular JS中用于IP地址验证的ng-pattern [重复]
【发布时间】:2015-08-28 19:23:47
【问题描述】:

我正在尝试使用 ng-pattern 验证文本框中的 IP 地址

代码:

<input name="machinestodiscover" type="text" ng-model="machinestodiscover" ng-minlength="7" ng-maxlength="15" ng-pattern="/\b([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})\b/" required>
 <span ng-show="conditionForm.machinestodiscover.$error.required" class="help-block" style="display:inline;">*Machines To discover Required</span>
 <span ng-show="conditionForm.machinestodiscover.$error.pattern" class="help-block" style="display:inline;">*IP Pattern Wrong.</span>

我面临的问题是它甚至接受 1.1.1.1.1.1.1 的值。

当我检查http://regexr.com/中的表达式时

截图:

我的正则表达式/ng-pattern 有什么问题

【问题讨论】:

标签: javascript html regex angularjs


【解决方案1】:

问题在于\b,它是单词边界。也就是.也被单词边界匹配了。

改用锚点,

^([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})$
  • ^ 将正则表达式锚定在字符串的开头。
  • $ 将正则表达式锚定在字符串的末尾

Regex Demo

【讨论】:

  • 完美的正则表达式。此外,为了使 IP 地址验证更加稳健,需要对每个 IPv4 地址段进行范围检查,即验证每个地址段是否介于 0 和 255 之间(包括两端)!
猜你喜欢
  • 2013-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-05
  • 1970-01-01
  • 2012-11-13
  • 2011-09-11
相关资源
最近更新 更多