Reputation: 24689
I am trying to use javascript regular expressions as pattern validators from within an Angular 2 template/form.
Here are my JS regexes defined as constants:
export class AppConstants {
static EMAIL_PATTERN = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,10}$/;
static FIRST_NAME_PATTERN = /^[a-zA-ZÀ-ÿ\s'-]+$/;
}
I import the regex from the constant within the component:
EMAIL_PATTERN = AppConstants.EMAIL_PATTERN;
Then within my html:
pattern="EMAIL_PATTERN"
However, even if the email address is valid, the validator triggers and marks the email field as invalid.
Here is the full template:
<div class="input-group">
<span class="input-group-addon">
<span class="glyphicon icon-email" aria-hidden="true"></span>
</span>
<input type="email"
ngControl="email"
#email="ngForm"
required
pattern="EMAIL_PATTERN"
[ngModel]="emailInfo.email"
(ngModelChange)="emailInfo ? emailInfo.email = $event : null"
placeholder="{{'EMAIL_FORM.NEW_ADDRESS'| translate }}"
class="form-control"
validateEmailAvailable/>
<span *ngIf="isSuccessFeedback(emailForm, email)" class="form-control-feedback" aria-hidden="true">
<span class="glyphicon icon-accept" aria-hidden="true"></span>
</span>
<span *ngIf="isErrorFeedback(emailForm, email)" class="form-control-feedback" aria-hidden="true">
<span class="glyphicon icon-close" aria-hidden="true"></span>
</span>
</div>
<div [hidden]="email.valid">
<div *ngIf="email?.errors?.required" class="control-label">{{'EMAIL_FORM.EMAIL_REQUIRED'| translate}}</div>
<div *ngIf="email?.errors?.pattern" class="control-label">{{'EMAIL_FORM.EMAIL_PATTERN'| translate}}</div>
<div *ngIf="email?.errors?.unavailable" class="control-label">{{'EMAIL_FORM.ALREADY_IN_USE'| translate}}</div>
</div>
</div>
Upvotes: 1
Views: 2066
Reputation: 657871
You would need
[pattern]="EMAIL_PATTERN"
to assign the value of EMAIL_PATTERN
instead of the string EMAIL_PATTERN
.
Currently you can't use bindings for pattern
or other validation rules like min
, max
, ... because they need to be static. There is an open issue to support that.
This was fixed in Angular2 final (from comments)
Upvotes: 1
Reputation: 5714
The pattern validator in Angular2 is currently based on the pattern attribute and thus only accepts strings and it follows the semantics of the HTML5 pattern attribute:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attr-pattern
Your HTML example only accepts a string of "EMAIL_PATTERN" in the input.
If you want to use your variable, I suggest using FormBuilder to define your control. Otherwise, you'll need to put the actual regex string in the pattern attribute directly.
Upvotes: 2