3

Am performing form validations using angular6 documentations and for now I ensured that all form validations are filled but now

Here is my question:

1.) How do I validate that Password and Confirm Password input value is not less than 6 characters and that both password field and confirm password field must match

2.) How do I ensure that email address entered is valid

  <form #r="ngForm" name="theForm" (submit)="reg(r)">
    <div class="form-group">
      <label>Username</label>
      <input type="text"
            class="form-control"
            name="username"
            [(ngModel)]="register.username"
            #registerUsername="ngModel"
            required
            pattern="^[a-zA-Z]+$">
      <span class="help-block danger" *ngIf="registerUsername.errors?.required && registerUsername.touched">
        The username is required
      </span>
      <span class="help-block danger" *ngIf="registerUsername.errors?.pattern && registerUsername.touched">
        The username can only contain the letters a-z or A-Z
      </span>
    </div>





    <div class="form-group">
      <label>Password</label>
      <input type="password"
            class="form-control"
            name="password"
            required
            [(ngModel)]="register.password"
            #registerPassword="ngModel">
      <span class="help-block danger" *ngIf="registerPassword.errors?.required && registerPassword.touched">
        password is required
      </span>
    </div>



 <div class="form-group">
      <label>Confirm Password</label>
      <input type="password"
            class="form-control"
            name="password"
            required
            [(ngModel)]="register.password"
            #registerPassword="ngModel">
      <span class="help-block danger" *ngIf="registerPassword.errors?.required && registerPassword.touched">
        Re-enter password is required
      </span>
    </div>





   <div class="form-group">
      <label>Email</label>
      <input type="email"
            class="form-control"
            name="email"
            required
            [(ngModel)]="register.email"
            #registerEmail="ngModel">
      <span class="help-block danger" *ngIf="registerEmail.errors?.required && registerEmail.touched">
        Email is required
      </span>
    </div>
2
  • 1
    email addresses must be validated through the email attribute or through the pattern one. Seeing you're using template-driven forms, you will have to create a directive on the form tag to validate password matching. For the length, a minlength attribute will be enough. Commented Oct 23, 2018 at 12:44
  • Thanks Sir. Your suggestion really help me find the solution Commented Oct 23, 2018 at 18:44

4 Answers 4

1

I tried to implement the requirements you stated, below is the link:

https://stackblitz.com/edit/angular-formvalidation-wins999-z1sxcw

I have used inbuilt validators for minimum length and to validate email

And a custom validator for password and confirm password match.

These links are useful:

https://angular.io/guide/forms-overview

https://material.angular.io/

I hope it helps

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

1 Comment

now your solution and my solution works for the same purpose but am selecting your answer for additional knowledge on angular materials. Thanks
0

This is how I was able to resolve it in case it might help someone.

    <div class="form-group">
      <label>Password</label>
      <input type="password"
            class="form-control"
            name="password"
            required  minlength="6"
            [(ngModel)]="register.password"
            #registerPassword="ngModel">
      <span class="help-block danger" *ngIf="registerPassword.errors?.required && registerPassword.touched">
        The password is required
      </span>

 <span *ngIf="registerPassword.errors?.minlength  && registerPassword.touched">
        Password must be at least 6 characters or longer.
      </span>

    </div>



  <div class="form-group">
      <label>Confirm Password</label>
      <input type="password"
            class="form-control"
            name="repassword"
            required  minlength="6"  pattern={{register.password}}
            [(ngModel)]="register.repassword"
            #registerRePassword="ngModel">
      <span class="help-block danger" *ngIf="registerRePassword.errors?.required && registerRePassword.touched">
        Confirm password is required
      </span>

 <span *ngIf="registerRePassword.errors?.minlength  && registerRePassword.touched">
        Password must be at least 6 characters or longer.
      </span>

  <span *ngIf="registerRePassword.errors?.pattern  && registerRePassword.touched">
        Passwords must match.
</span>

    </div>



   <div class="form-group">
      <label>Email</label>
      <input type="email"
            class="form-control"
            name="email"
            required  pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$"
            [(ngModel)]="register.email"
            #registerEmail="ngModel" email>
      <span class="help-block danger" *ngIf="registerEmail.errors?.required && registerEmail.touched">
        Email is required
      </span>


<span *ngIf="registerEmail.errors?.pattern  && registerEmail.touched">
       Valid Email is required
      </span>

    </div>

Comments

0

Try to use reactive forms in angular, to my mind it's more readable and flexible. You can start from here. Your form will look like:

<div [formGroup]="myForm" #form>
      <label>Username</label>
      <input formControlName="username" type="text">
      <label>Password</label>
      <input formControlName="password" type="password">
      <label>Confirm Password</label>
      <input formControlName="confirmPassword" type="password">
      <label>Email</label>
      <input formControlName="email" type="text">
      <button (click)="submit()" [disabled]="form.invalid">Submit</button>
    </div>

Than build your form in .ts file using FormBuilder like that:

myForm: FormGroup;
constructor(private builder: FormBuilder) {
  this.myForm = builder.group( {
    username: [null, Validators.required],
    password: [null, [Validators.required, Validators.minLength(6)]],
    confirmPassword: [null, Validators.required],
    email: [null, [Validators.required, Validators.email]]
    }, {validator: PasswordValidator.matchPassword});
   }

To validate length, email and some more stuff you can use built-in validators, but for password matching you should write some more code. I wrote it in separates file PasswordValidator.ts. It looks like:

export class PasswordValidator {
  static matchPassword(control: AbstractControl) {
    const password = control.get('password').value;
    const confirmPassword = control.get('confirmPassword').value;
    if (password !== confirmPassword) {
      control.get('confirmPassword').setErrors({matchPasswords: true});
    }
    return null;
  }
}

Comments

0

Please check the following.

Html.

          <mat-form-field class="full-width-input">
              <input matInput type="password" formControlName="newpassword" placeholder="Enter new password"
                [type]="hide1 ? 'password' : 'text'" required minlength="4" maxlength="25"
                text="test" #newpassword>
              <mat-icon matSuffix class="pointer-style" (click)="hide1 = !hide1" >
                {{hide1 ? 'visibility_off' : 'visibility'}}</mat-icon>
                <mat-error *ngIf="form.controls['newpassword'].hasError('required')">
                   New Password is <strong>required</strong>
                  </mat-error>
              <mat-error *ngIf="form.controls['newpassword'].hasError('minlength')">
                Your password must be at least <strong>4 characters. </strong>
            </mat-error>
            </mat-form-field>


            <mat-form-field class="full-width-input">

                <input matInput type="password" placeholder="Confirm password" formControlName="conformpassword" [errorStateMatcher]="matcher"
                  [type]="hide2 ? 'password' : 'text'" text="test" #conformpassword>
                <mat-icon matSuffix class="pointer-style" (click)="hide2 = !hide2">
                  {{hide2 ? 'visibility_off' : 'visibility'}}</mat-icon>
                  <mat-error *ngIf="form.hasError('notSame')">
                      Passwords does not match
                  </mat-error>

              </mat-form-field>
          <div class="full-width-input">

          </div>
          <button  style="margin-left: 75px;" mat-raised-button [disabled]="!form.valid" color="primary">SUBMIT</button>
        </form>

in component:

  1. import {ErrorStateMatcher } from '@angular/material';

    export class MyErrorStateMatcher implements ErrorStateMatcher {
    
      isErrorState(control: FormControl | null, form: FormGroupDirective
    | NgForm | null): boolean {
    
        const invalidCtrl = !!(control && control.invalid && control.parent.dirty);
        const invalidParent = !!(control && control.parent && control.parent.invalid && control.parent.dirty);
    
        return (invalidCtrl || invalidParent);   } } @Component({   selector: 'app-changepassword',   templateUrl:
    './changepassword.component.html',   styleUrls:
    ['./changepassword.component.scss'] }) export class
    ChangepasswordComponent implements OnInit {   form: FormGroup;  
    error = '';   formSubmitAttempt: boolean;   oldPassword:
    FormControl;   newpassword: FormControl;   conformpassword:
    FormControl;   hide: boolean;   hide1: boolean;   hide2: boolean;  
    matcher = new MyErrorStateMatcher();
    
    constructor(private fb: FormBuilder) {
    
    
            this.form = this.fb.group({
              oldPassword:  ['', Validators.compose([Validators.required, Validators.minLength(4),
    Validators.maxLength(25)])],
              newpassword:  ['', Validators.compose([Validators.required, Validators.minLength(4),
    Validators.maxLength(25)])],
              conformpassword:  ['']
    
            }, {validator: this.checkPasswords });
            dialogRef.disableClose = true;
        }
    
        checkPasswords(group: FormGroup) { // here we have the 'passwords' group
        let pass = group.controls.newpassword.value;
        let confirmPass = group.controls.conformpassword.value;
    
    
        return pass === confirmPass ? null : { notSame: true }   }
    
    
      ngOnInit() {
        this.hide = true;
        this.hide1 = true;
        this.hide2 = true;   }
    
    }
    

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.