1

I am trying to validate IP Address in the text box with ng-pattern

CODE:

<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>

The problem I am facing is that it is even accepting value as 1.1.1.1.1.1.1.

where as I checked the expression in http://regexr.com/

Screenshots:

enter image description here

enter image description here

enter image description here

What is wrong in my regex/ng-pattern

Sonam G
  • 118
  • 1
  • 15
  • 1
    Try regex provided in http://stackoverflow.com/questions/10006459/regular-expression-for-ip-address-validation – Satpal Aug 28 '15 at 11:21

1 Answers1

3

The problem is with \b which is word boundary. That is . is also matched by the word boundaries.

Use anchors instead,

^([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})$
  • ^ Anchors the regex at the start of the string.
  • $ Anchors the regex at the end of the string

Regex Demo

nu11p01n73R
  • 26,397
  • 3
  • 39
  • 52
  • Perfect RegEx. Also, to make the IP address validation more robust, range checking for each IPv4 address segment to be done, i.e. to validate that each address segment is between 0 and 255 (both end inclusive)! – Vikrant Jul 07 '17 at 05:38
  • https://regex101.com/r/HBTDi1/1 – Frederik De Ruyck Apr 10 '19 at 15:03