I have a textbox and a button. Textbox input is a url and there is a method for validating url format which is isUrlFormatValid() in this example.
If isUrlFormatValid() fails then there is an error message appears at below of textfield and the button becomes passive and cannot be clicked. But my problem is when the page first loaded, this method result automatically comes as false so directly error message appears for empty box as well.
<mat-card class="">
<mat-card-content fxLayout="row wrap" fxLayoutAlign="left" fxLayoutGap="15px">
<div>
<mat-form-field>
<mat-label>Enter link here</mat-label>
<input type="url" matInput [(ngModel)]="domainName">
</mat-form-field>
<mat-error *ngIf="isUrlFormatValid()">
Please enter the link in correct format
</mat-error>
</div>
</mat-card-content>
<div>
<button type="button" id="search" class="" [disabled]="isUrlFormatValid()"
(click)="addClicked()">Add Domain
</button>
</div>
</mat-card>
And method definition in ts file is:
isUrlFormatValid() {
const pattern = /^((((https?)(:\/\/))?((www)\.)?)?|mailto:(\w+\.?\w+)\@)([a-z0-9]+\.[a-z0-9]+)+$/;
if (pattern.test(this.domainName)) {
return false;
}
return true;
}
if i change the line in ts file:
if (pattern.test(this.domainName))
to:
if (pattern.test(this.domainName) || this.domainName == null)
then error message problem is solved but this time button comes as clickable at startup, if i write something yes it is working but when the page is first loaded its coming as active.
So how can i solve this problem ?