I am working on an Ionic app and trying to create a regular expression to match a website URL for some form validation. Here is the regex I am using:
^((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?$
While I know that this is not a “perfect” regex for validating a URL, I am getting inconsistencies between using the regex in ionic vs. my web tests.
For example, i plugged the same regex into http://www.regex101.com and several examples are working just fine:
However, when I run my ionic app, none of my patterns are matching.
I know that I am using Validators.pattern() properly because I have already added a regex validator for email inputs. I also know that I’m using it properly because I am able to plug in simple regex patterns, like http and the validation works fine.
Somewhere along the way, the Ionic pattern is failing to parse as a normal regex would. Perhaps my pattern is using a character that Ionic does not recognize or parses differently?
Is there something about using regex in Ionic that I am missing?
Here is how I am setting up the validations for my various form controls. Note that the pattern for organizerEmail is working.
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: [''],
});
Here is the HTML input uses the form control:
<ion-item>
<ion-label stacked color="light">Website</ion-label>
<ion-input formControlName="eventUrl" type="url" placeholder="Website"></ion-input>
</ion-item>
\again. Replace\/with/. Remove^and$. E.g.Validators.pattern('^((http|ftp|https)://)?([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?$')https?matches bothhttpandhttps, is quicker and shorter. The token\wincludes_, so you don't need to add it to the character class.