angular - 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
解决方案
如果您在控制器中定义正则表达式:
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>
推荐阅读
- java - 如何在 Android Studio 中处理用户管理?
- azure - Azure Storage SDK for .NET:如何在新的 Blob 存储库上设置 RetryPolicy?
- python - ValueError:无法解析相关模型
- java - 在没有 ffmpeg 的情况下在 android 上修剪或拆分作品
- node.js - 请帮我nestjs套接字为什么ERR_SSL_PROTOCOL_ERROR?
- testing - 调用 cy.get('body') 后我无法选择元素
- html - 在悬停时激活菜单子项
- gravityforms - 自动激活重力表单中的下一个按钮
- automation - 如何自动上传 Bing Maps 数据?
- python - 在云函数中运行数据流