3

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

1
  • 1
    Instead of using regex you might try to create a URL and return true if it succeeds or false, if it throws an exception. You'd need to write your own validator then, of course. Commented Aug 25, 2018 at 15:02

2 Answers 2

8

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();
  }
Sign up to request clarification or add additional context in comments.

5 Comments

Hi, it is better but if you enter first time and the url is not valid you are not getting immediately the invalid message for invalid url
yes because it activate on touched . you need to set it touched if you want. depends on you. <mat-error> activate on first (blur).
Many thanks for your. It is exactly what I need. But I guessed it would be easier then write own functions to handle
yes you can write it depends on the no. of validation. you can also create common message template to large no of validations.
doesnt seem to accept "cnn.com" as valid though, I have the same thing in my code right now but facing the same issue
2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.