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.
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}$";
Try Validators.pattern(/^[a-zA-Z0-9_-]*$/)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With