Angular6 form validations

angular 8 form validation example
custom validator angular
angular 4 form validation on submit example
angular 5 form validation example
angular async validator
angular material form validation
angular 6 template-driven form validation example
custom validation in angular 6 reactive form

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>

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

Angular 6, A quick example of how to implement validation in Angular 6 using Reactive Forms. The example is a simple registration form that validates on  AngularJS is constantly updating the state of both the form and the input fields. They are all properties of the input field, and are either true or false. They are all properties of the form, and are either true or false. You can use these states to show meaningful messages to the user.

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>

Angular 6, A quick example of how to implement validation in Angular 6 using Template-​Driven Forms. The example is a simple registration form that  The form binds the form submit event to the onSubmit() handler in the app component using the Angular event binding (ngSubmit)="onSubmit()". Validation messages are displayed only after the user attempts to submit the form for the first time, this is controlled with the submitted property of the app component.

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>

Angular Form Validation Example Tutorial, We are going to create a form with one input for just basic understanding for Angular Forms. First, we need to include Reactive Form in app.module.ts file. // app. Angular 6 Form Validation App Component The angular 6 app component binds the HTML form elements and HYML validators and displayed some custom message for our signup form using an Angular6 FormBuilder to make an instance of a StudentGroup that is more data all the HTML stored in the signupForm property.

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;   }
    
    }
    

angular-6-reactive-form-validation, Toggle light/dark theme. Toggle Zen Mode. Project. Download Project. Info. Angular 6 - Reactive Forms Validation Example. 311.2k. 551. Files. app. New File​. Angular Reactive Forms offer an easy way to use reactive patterns and validations. Angular reactive forms follow the reactive programming style that supports the explicit data management flow between non-UI data models and a UI-oriented form model that keeps tracking the states and values of HTML controls on the screen.

Angular 6 Form Validation Example Tutorial, Angular 6 Form Validation Example Tutorial. We will use Angular Reactive Form Validation. FormGroup, FormControl, FormArray, and  An Angular form is a regular HTML form with few additional features. For each field (input, radio, select, etc.) in the form, we need an object of the FormControl class. The FormControl object gives information about that field. Its value, if the value is valid, and if it is not valid what are the validation errors, etc.

Form validation in angular 6, Take a look at code below. login.component.html <form novalidate [formGroup]="​loginForm"> <div id="login-container"  Angular reactive forms, also known as model-driven forms, offers an easy way to use reactive patterns and validations. They follow the reactive programming style that supports an explicit data management flow between non-UI data models (frequently retrieved from a server) and a UI-oriented form model that keeps the states and values of HTML

Angular 6 Reactive Forms Validation Example, Interested to learn more about Angular 6? Then check out our detailed example on Angular 6 Reactive Forms Validation! Angular 6 - Form Validation on blur. Ask Question Asked 1 year, 9 months ago. Active 1 year ago. Viewed 9k times 1. I want to validate input filled in onBlur how can

Comments
  • 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.
  • Thanks Sir. Your suggestion really help me find the solution
  • now your solution and my solution works for the same purpose but am selecting your answer for additional knowledge on angular materials. Thanks