0

I have this regular expression, to validate Ipv4 and Ipv6 address

ng-pattern='/^(?=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)(?:(?:25[0-5]|[12][0-4][0-9]|1[5-9][0-9]|[1-9]?[0-9])\.?){4}$|(?=^(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$)(?![^:]*::.+::[^:]*$)(?:(?=.*::.*)|(?=\w+:\w+:\w+:\w+:\w+:\w+:\w+:\w+))(?:(?:^|:)(?:[0-9a-f]{4}|[1-9a-f][0-9a-f]{0,3})){0,8}(?:::(?:[0-9a-f]{1,4}(?:$|:)){0,6})?$/'

But If I leave my field empty, the pattern validates the text.

I need to add in this regex the fact that the field musn't be empty.

Thanks

galiolio
  • 275
  • 3
  • 19
  • maybe have a lookie here: https://stackoverflow.com/questions/23483855/javascript-regex-to-validate-ipv4-and-ipv6-address-no-hostnames – sniperd Aug 22 '17 at 15:53
  • I didn't find an answer to my question. My regex for ipv4 and ipv6 is working, but I need to add the fact that the field cannot be empty in this regex. – galiolio Aug 22 '17 at 16:01
  • Add `(?=.)` after `^`. Also, perhaps, add `ng-trim="false"` – Wiktor Stribiżew Aug 22 '17 at 20:49

1 Answers1

1

Add the required attribute to the <input> element:

<form name="form1">
  <input ng-model="data" name="input1" required
         ng-pattern='/^(?=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)(?:(?:25[0-5]|[12][0-4][0-9]|1[5-9][0-9]|[1-9]?[0-9])\.?){4}$|(?=^(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$)(?![^:]*::.+::[^:]*$)(?:(?=.*::.*)|(?=\w+:\w+:\w+:\w+:\w+:\w+:\w+:\w+))(?:(?:^|:)(?:[0-9a-f]{4}|[1-9a-f][0-9a-f]{0,3})){0,8}(?:::(?:[0-9a-f]{1,4}(?:$|:)){0,6})?$/'
  />
</form>

The "required" validator will check if the input is empty.

The DEMO

<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app>
    <form name="form1">
      <input ng-model="data" name="input1" required
             ng-pattern='/^(?=\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$)(?:(?:25[0-5]|[12][0-4][0-9]|1[5-9][0-9]|[1-9]?[0-9])\.?){4}$|(?=^(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}$)(?![^:]*::.+::[^:]*$)(?:(?=.*::.*)|(?=\w+:\w+:\w+:\w+:\w+:\w+:\w+:\w+))(?:(?:^|:)(?:[0-9a-f]{4}|[1-9a-f][0-9a-f]{0,3})){0,8}(?:::(?:[0-9a-f]{1,4}(?:$|:)){0,6})?$/'
      />
    </form>
    <br>
    {{data}}
    <br>
    Form1 input1 valid - {{form1.input1.$valid}}
    <div ng-show="form1.$invalid">
    ERROR: {{form1.input1.$error}}
    </div>
    
  </body>
Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95