Reputation: 298
I need to come up with a validation pattern in Reactive Form (Form Control) using Validators.pattern. The conditions are Alphanumeric, Only underscore_, hyphen- are allowed. Any type of space should not be allowed. Is there any one single pattern that will help me achieve this.
Thanks.
Upvotes: 9
Views: 28504
Reputation: 49
It works for me.
In .ts file write the following code.
pattern="^[ a-zA-Z][a-zA-Z ]*$";
this.projectRoleAssignFrom = this.formBuilder.group({
userName : [''],
userRole : [''],
project : [''],
searchInput : ['', Validators.pattern(this.pattern)]
})
in html file wrire the following code.
<div class="form-group">
<mat-form-field>
<mat-select placeholder="Select User" formControlName="userName"
(click)="clearSearchField()">
<div class="searchbar">
<md-input-container class="full-width-ex" color="accent">
<input mdInput #input type="text" class="searchbar-input"
(input)="filterAssociates($event.target.value)" placeholder="Search User"
formControlName="searchInput">
</md-input-container>
<mat-error class="alert-danger" *ngIf="projectRoleAssignFrom.get('searchInput').hasError('pattern')" >
Invalid User</mat-error>
</div>
<mat-option *ngFor="let user of filteredAssociatesList" [value]="user.fullName"
(click)="getValues('user', user.id)">
{{ user.fullName }}
</mat-option>
<!-- <mat-error *ngIf="userName.invalid && userName.touched"></mat-error> -->
</mat-select>
</mat-form-field>
</div>
Upvotes: 3
Reputation: 1353
try this
pattern1 = "^[0-9_-]{10,12}$";
phone: ['', [Validators.required, Validators.pattern(this.pattern1)]]
Upvotes: 0
Reputation: 306
Validators.pattern with FormBuilder
We can use Validators.pattern
for pattern validation while creating form either by FormBuilder
or by FormGroup
. Here we will provide code snippet for FormBuilder
.
unamePattern = "^[a-z0-9_-]{8,15}$";
userForm = this.formBuilder.group({
username: ['', Validators.pattern(this.unamePattern)],})
But if you dont want to allow "-" just use this
unamePattern = "^[a-z0-9_]{8,15}$";
Upvotes: 11