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 ?
You may achieve the same without using an extra function. Just use some template driven form attributes & its control states as mentioned below. Also, It is a good practice to enclose your form elements in a
<form>
tag. So, if you use form, your scenario would be -
Simply add this to your component class -
public pattern = /^((((https?)(:\/\/))?((www)\.)?)?|mailto:(\w+\.?\w+)\@)([a-z0-9]+\.[a-z0-9]+)+$/;
And Your HTML would be -
<form #f="ngForm" (ngSubmit)="addClicked()">
<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" #url="ngModel" [class.is-invalid]="url.invalid && url.touched"
name="url" [pattern]="pattern" required>
</mat-form-field>
<mat-error *ngIf="url.invalid && (url.dirty || url.touched)">
Please enter the link in correct format
</mat-error>
</div>
</mat-card-content>
<div>
<button type="button" id="search" class="" [disabled]="!f.valid">Add
Domain
</button>
</div>
</mat-card>
</form>