Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material url validation with pattern

Helo,

I am working with Angular Material and I have created an form field and I want to validate my url but it is not working. I tried with email and it is working. I want also that the button should be disabled until I enter a valid url:

Here is my code:

export class StartComponent implements OnInit {
  searchValue: string;
  url: any;
  public reg = /[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi;

  constructor() {  }
  ngOnInit() {
    this.url = new FormControl('', [Validators.required, Validators.pattern(this.reg)]);
    this.getErrorMessage();
  }
  getErrorMessage() {
    return this.url.hasError('required') ? 'You must enter a value' :
        this.url.hasError('email') ? 'Not a valid url' :
            '';
  }
}

HTML

<mat-card class="searchbox">
    <mat-form-field>
        <input matInput placeholder="Enter your url" [formControl]="url" required>
        <mat-error *ngIf="url.invalid">{{getErrorMessage()}}</mat-error>
    </mat-form-field>
    <!--Here button should be disabled if url not valid and until there is something entered-->
    <button mat-stroked-button color="warn">GO</button>
</mat-card>

Here is the the app at stackblitz

like image 990
Noah Tony Avatar asked Jun 08 '26 23:06

Noah Tony


2 Answers

Try like this:

DEMO

<mat-card class="searchbox">
    <mat-form-field>
        <input (focus)="markTouched()" matInput placeholder="Enter your url" [formControl]="url" required>
        <mat-error *ngIf="url.hasError('required')">
      Url required
    </mat-error>
    <mat-error *ngIf="url.hasError('pattern')">
      Url Pattern Invalid
    </mat-error>
    </mat-form-field>
    <!--Here button should be disabled if url not valid and until there is something entered-->

    <button [disabled]="url.invalid" mat-stroked-button color="warn">GO</button>
</mat-card>

{{url.errors | json}}

TS:

public myreg = /(^|\s)((https?:\/\/)?[\w-]+(\.[\w-]+)+\.?(:\d+)?(\/\S*)?)/gi

  url = new FormControl('', [Validators.required, Validators.pattern(this.myreg)]);

 markTouched() {
    this.url.markAsTouched();
    this.url.updateValueAndValidity();
  }
like image 141
Akj Avatar answered Jun 11 '26 17:06

Akj


HTML

<mat-error *ngIf="form.get('url').hasError('pattern')">Invalid URL format</mat-error>

TS

ngOnInit(): void {
    this.form = this.formBuilder.group({url: [null, [Validators.required, YourComponent.urlValidator});
}

private static urlValidator({value}: AbstractControl): null | ValidationErrors {
    try {
       new URL(value);
       return null;
    } catch {
       return {pattern: true};
    }
}

You can validate it simply using built-in URL API https://developer.mozilla.org/en-US/docs/Web/API/URL.
urlValidator method returns null if provided control's url value is valid, 'pattern' error otherwise.

like image 21
Vlad Avatar answered Jun 11 '26 15:06

Vlad