首页 > 解决方案 > Validation using Regex using angular 7

问题描述

I have a URL in the anchor tag.I want to display the the URL only if its valid, if its invalid I want to hide the anchor tag.

How can I do the pattern matching with regular expression?

For example I have something like mentioned below, how can I modify it so that if it doesnt have a valid url then it should be hidden

 <a  class="col-sm-6" [href]="fg.url.value">{{
      fg.value
    }}</a>

The regular expression that am using is like below

var expression = "/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi"; 

I more have a separate formgroup and I reference it in my component. My FormGroup looks like this

export class SIFormGroup extends FormGroup {

    if (!data) {
      data = new SI();   //Where SI has one element as URL
    }
    var expression = "/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/gi"; 
            var regex = new RegExp(expression); 
    const model = toFormDataModel(data);
    if(!model.URL.match(regex)){
       model. URL ='';
    }
}

model.URL.match(regex) returns null, I don’t get any value in that

标签: angular

解决方案


如果您在控制器中定义正则表达式:

expression = /[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)?/gi;

那么只有当 url 与表达式匹配时,您才能使用 *ngIf 来显示您的链接:

 <a *ngIf="fg.url.value.match(expression)" class="col-sm-6" [href]="fg.url.value">{{
      fg.value
    }}</a>

推荐阅读