I have angular 8 application and I want to validat for correct youtube url and vimeo url with pattern. Or Pipe?
So I have this:
<ng-container *ngIf="is('VideoDisplay')">
<iframe
*ngIf="videoUrl.value"
class="video-iframe"
type="text/html"
[src]="getVideoSafeUrl(videoUrl.value)"
frameborder="0"
allowfullscreen
></iframe>
<mat-form-field>
<input
matInput
type="url"
name="videoUrl"
ngModel
#videoUrl="ngModel"
placeholder="Url of video"
i18n-placeholder
pattern="^(http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+"
required
/>
<mat-error>
<app-element-edit-field-error
[errors]="videoUrl.errors"
></app-element-edit-field-error>
</mat-error>
</mat-form-field>
</ng-container>
But this is only validates for youtube. But I also want to combine it with Vimeo movies. So I have this regular expression for vimeo:
var re = /\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+)/i;
But how to combine this two now? And use it with a Pipe? So that you can use it in every template?
Thank you
So I created a pipe like this:
export class VideoUrlPipe implements PipeTransform {
transform(value: any, args?: any): any {
const vimeoReg = new RegExp(/\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+)/i);
const youtubeReg = ^(http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+;
return null;
}
}
I have it now like this:
export class RegexConstants {
static readonly videoUrlsRegexConstant =
/((http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+)|(\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+))/g;
}
You am combine the two regex. Final regex
re = /((http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?(\.com)?\/.+)|(\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+))/g
For reusing this in every template, you can make a constants file and keep this variable there. Then just import it where you want to use it. No need of pipe there.
export class regexConstants {
static readonly videoUrlsRegexConstant = /((http(s)?:\/\/)?((w){3}.)?youtu(be|.be)?
(\.com)?\/.+)|(\/\/(?:www\.)?vimeo.com\/([0-9a-z\-_]+))/g;
....
....
....
}
You can define other regex also in this file and reuse it everywhere in your application.
import {regexConstants} from 'path/to/regexConstants';
re = regexConstants.videoUrlsRegexConstant;
html:
<mat-form-field>
<input
matInput
type="url"
name="videoUrl"
ngModel
#videoUrl="ngModel"
placeholder="Url of video"
i18n-placeholder
pattern="{{re}}"
required
/>