7

I am using a reactive form in angular 6, and trying to do some validation on a password field. Basically it needs to be more than 8 characters, contain at least 1 upper case, and contain at least 1 symbol.

my regex which I have tested, is ^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})

Here is an excerpt from my login component ts:

  ngOnInit() {
        this.loginForm = this.formBuilder.group({
            userName: ['Username', [Validators.required]],
            password: ['Password', [Validators.pattern("^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})")]]            
        });
    }

Here is my form group div:

 <div class="form-group">
                      <input type="password" formControlName="password" class="form-control" [ngClass]="{ 'is-invalid': submitted && f.password.errors }" />
                      <div *ngIf="submitted && f.password.errors" class="invalid-feedback">              
                          <div *ngIf="f.password.errors.pattern">Password must contain more than 8 characters, 1 upper case letter, and 1 special character</div>
                      </div>
                  </div>

Basically the password does not validate even if it appears to be correct. Any tips would be appreciated.

2
  • can you give a "valid" password ? Commented Sep 28, 2018 at 20:01
  • for example, Superman***** should work Commented Sep 28, 2018 at 20:04

5 Answers 5

23

ng-pattern seem to take a regExp as parameter (like in angularJs) :

Validators.pattern(new RegExp("^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,}))")

You can also use /..../

Validators.pattern(/^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=.{9,})/)

Should work ;)

Sign up to request clarification or add additional context in comments.

4 Comments

than you so much!
The second option wok as a charm
thanks have tried second option and it's working perfectly.
You are a freaking genius!
1

I think it's due to the *ngIf condition in your HTML.]

Try *ngIf="loginForm.controls.password.hasError('pattern')"

Comments

1
 pattern1 =  "^[0-9_-]{10,12}$";
 phone: ['', [Validators.required, Validators.pattern(this.pattern1)]]

Comments

0

You need to use the /.../ in the pattern and to add the required validator this is a link for working example https://stackblitz.com/edit/angular-rkxs3q

<h1 class="title">validation</h1>

<hr/>

<form class="user-form" [formGroup]="userForm" (submit)="onSubmit()">

<div class="form-group">
    <label for="type">User type:</label>
    <select id="type" formControlName="type">
  <option disabled value="null">please select user type</option>
  <option *ngFor="let userType of userTypes">{{userType}}</option>
</select>
</div>

<div class="form-group">
    <label for="name">User Name:</label>
    <input type="text" id="name" formControlName="name" />
</div>



<div class="form-group">
    <label for="address">User  address:</label>
    <input type="text" id="address" formControlName="address" />
</div>

<div class="form-group">
    <label for="password">password:</label>
    <input type="text" id="password" formControlName="password" />
</div>
 <div class="error"
 *ngIf="!userForm.get('password').valid && userForm.get('password').touched">
Password must contain more than 8 characters, 1 upper case letter, and 1 
special 
character
</div>

 <button type="submit">submit</button>
   </form>
   <hr/>

the Typescript

import { Component, OnInit, OnDestroy } from '@angular/core';
import { FormBuilder, FormGroup, Validators, ValidatorFn, FormControl, 
 ValidationErrors } from '@angular/forms';
 import { Subscription } from 'rxjs';
import { Observable } from 'rxjs';



 @Component({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
  })
 export class AppComponent implements OnInit {
 userForm: FormGroup;
  userTypes: string[];

 private userTypeSubscription: Subscription;

 constructor(private fb: FormBuilder) { }

  ngOnInit() {
this.userTypes =["Custumer","Admin","Super Admin"]
 this.userForm = this.fb.group({
  type: [null, [Validators.required]],
  name: [null, [
    Validators.required,
    Validators.pattern(/^[A-z0-9]*$/),
    Validators.minLength(3)]
  ],
  address: null,
  password: [null, [
    Validators.required,Validators.pattern(/^(?=.*[A-Z])(?=.*[!@#\$%\^&\*])(?=. 
     {9,})/)]
  ]
});
  }
 }

Comments

0

Check the type attribute of your input if you want to validate numeric values. If it's a number type input, then some browser will not pass any non-numeric value to the validator, thus you will have a required error in your map, if you declared a Validators.required in the validator array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.