Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 5 Reactive Form Pattern Validators

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.

like image 212
Srihari GouthamGr Avatar asked Jul 03 '18 07:07

Srihari GouthamGr


2 Answers

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}$";
like image 175
Wealsegun Avatar answered Sep 24 '22 19:09

Wealsegun


Try Validators.pattern(/^[a-zA-Z0-9_-]*$/)

like image 39
Guerric P Avatar answered Sep 24 '22 19:09

Guerric P