1

I'm having a problem validating an IPv4 form field using Angular2 reactive forms.

I define the form field like this:

this.formModel.addControl('address', new FormControl('', this.ipAddressValidator.bind(this)));

The validator function is:

ipAddressValidator(control: FormControl): {[key: string]: any} {
  const value: string = control.value || '';
  let valid;
  let ipVersion : string;

  if(this.formModel.controls['ip_version']) 
    ipVersion = this.formModel.controls['ip_version'].value;

  if(ipVersion == 'IPv6')
    valid = value.match(this.ipV6Regexp);
  else
    valid = value.match(this.ipV4Regexp);   // By default, consider the address as IP V4

  return valid ? null : { ip: true };
}

Basically, it checks the value of an HTML select tag ('ip_version') and sets the regular expression to either IPv4 or IPv6. The variable that holds the IPv4 regular expression is 'this.ipV4Regexp', and its value is:

public ipV4Regexp : string = 
"^(?:(?: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]?)$";

The problem is that the form accepts values as '192.168' or '192.168.10', when the regular expression specifies clearly to accept only {3} blocks of numbers, followed by a last one. If I go to test the expression to https://regex101.com/, it works fine and only accepts addresses with 4 blocks of numbers.

Isn't the regular expression right? Thanks,

Fel
  • 4,428
  • 9
  • 43
  • 94

0 Answers0