Hey there, I'm currently trying to implement a validator for an IP address in Angular. Strangely, even when I input an invalid IP address like 12.2.2.2...
, the GUI indicates it is valid (as shown in the image). However, the console logs reveal that it is actually a pattern mismatch (indicating an incorrect pattern detection). I'm feeling puzzled as to what might be missing. It's becoming confusing now and I could really use another set of eyes to pinpoint the issue.
Just to clarify, the required aspect is functioning properly with ipaddress
. My confusion lies in why it's not working on pattern validation. Please refer to the image below
https://i.sstatic.net/uyh7d.png
Here is my code example on StackBlitz
Below you can find the structure of my code:
HTML Section:
<div class="form-group row required" [ngClass]="{
'is-invalid': ipaddress.invalid && (ipaddress.dirty || ipaddress.touched),
'is-valid': ipaddress.valid && (ipaddress.dirty || ipaddress.touched)
}">
<label for="ipaddress" class="col-sm-3 col-form-label">IP Address</label>
<div class="col-sm-7">
<input type="text" class="form-control" placeholder="IP Address"
id="ipaddress" name="ipaddress" formControlName="ipaddress"
ngbAutofocus required>
<div class="form-control-feedback invalid-feedback"
*ngIf="ipaddress.errors">
<p *ngIf="ipaddress.errors.required">IP Address is required</p>
<p *ngIf="ipaddress.errors.pattern">Invalid IP Address format</p>
</div>
</div>
</div>
TS File:
this.ipaddress = new FormControl('', {
validators: Validators.compose([
Validators.required,
Validators.pattern('(?:(?: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]?)')
])
});