我正在开发一个Ionic应用程序并尝试创建一个正则表达式来匹配网站URL以进行某些表单验证。这是我正在使用的正则表达式:
^((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?$
虽然我知道这不是用于验证URL的“完美”正则表达式,但是在离子与我的Web测试中使用正则表达式之间存在不一致。
例如,我将相同的正则表达式插入http://www.regex101.com并且几个示例正常工作:
但是,当我运行我的离子应用程序时,我的模式都没有匹配。
我知道我正在使用Validators.pattern()
,因为我已经为电子邮件输入添加了一个正则表达式验证器。我也知道我正在使用它,因为我能够插入简单的正则表达式模式,如http
,验证工作正常。
在某个地方,离子模式无法像正常的正则表达式那样解析。也许我的模式使用的是Ionic无法识别或解析的角色?
有没有关于在Ionic中使用正则表达式的东西,我错过了?
以下是我为各种表单控件设置验证的方法。请注意,organizerEmail的模式正在运行。
let formGroup: FormGroup = this.formBuilder.group({
title: ['', Validators.required],
venue: ['', Validators.required],
streetAddress: ['', Validators.required],
city: ['', Validators.required],
zipCode: ['', Validators.required],
price: [''],
description: ['', Validators.compose([Validators.maxLength(this.descriptionMax), Validators.required])],
eventUrl: ['', Validators.compose([Validators.pattern('^((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?$'), Validators.required])],
contactName: ['', Validators.required],
organizerEmail: ['', Validators.compose([Validators.pattern('^[a-zA-Z0-9._]+[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$'), Validators.required])],
phoneNumber: [''],
});
这是HTML输入使用表单控件:
<ion-item>
<ion-label stacked color="light">Website</ion-label>
<ion-input formControlName="eventUrl" type="url" placeholder="Website"></ion-input>
</ion-item>
您可以通过转义反斜杠来修复模式,您可以删除锚点,因为它们是由引擎隐式添加的。您也可以删除不必要的组。
使用
Validators.pattern('(?:(?:(?:ht|f)tp)s?://)?[\\w_-]+(?:\\.[\\w_-]+)+([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?')
这是regex demo。
电子邮件检查正则表达式也必须正确地逃避.
:
Validators.pattern('[a-zA-Z0-9._]+[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,4}')