Search code examples
angularangular-ui-routerangular-materialangular-directive

Angular Reactive Validation


I am new to angular, I want to know how the reactive validation works in angular 6.0, I am trying to do the validation from last 2 weeks, can someone help me to do the validation? and teach me how to do it.

your help is highly appreciated, Thank you :)

import { Component } from '@angular/core';
import { ReactiveFormsModule, FormsModule, FormGroup, FormBuilder, FormControl, Validators  } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'AngularProject';

  constructor(private fb:FormBuilder) 
  {}
  profileForm : FormGroup;
  submitted = false;
  ngOnInit(): void {
        this.profileForm= this.fb.group({
          firstName:['', [Validators.required]],
          EmailMe:['',[Validators.required]]
        });
  }

  onSubmit():void
  {
    this.submitted = true;
    if (this.profileForm.invalid) {
      return;
  }
    console.log(this.profileForm.value);
    alert('SUCCESS!! :-)\n\n' + JSON.stringify(this.profileForm.value))
  }
  get f() { 
    return  this.profileForm.controls; 
}}

The HTML part is given below.

<form class="form-horizontal" [formGroup]="profileForm" (ngSubmit)="onSubmit()">
  <div class="panel panel-primary">

    <div class="panel-heading">
      <h3 class="panel-title">C3</h3>
    </div>


  <div class="panel-body">
      <div class="form-group">
        <label class="col-sm-2 control-label" for="fullName">Full Name</label>
        <div class="col-sm-8">
          <input id="fullName" type="text" class="form-control" formControlName="firstName"
          [ngClass]="{ 'is-invalid': submitted && f.profileForm.errors }" >

          <div *ngIf="f.firstName.errors.required">First Name is required {{f.profileForm.errors}}</div>
          <div *ngIf=></div>
        </div>
      </div>

      <div class="form-group">
        <label class="col-sm-2 control-label" for="email">Email</label>
        <div class="col-sm-8">
          <input id="email" type="text" class="form-control" formControlName="EmailMe">
        </div>
      </div>

  </div>
    <div class="panel-footer">
      <button class="btn btn-primary" type="submit" [disabled]="!profileForm.valid">Save</button>
    </div>
  </div>
</form>
 <!--  -->

<router-outlet></router-outlet>

Solution

  • Your validation check seems to be wrong. Here, give this a try:

    <form 
      class="form-horizontal" 
      [formGroup]="profileForm" 
      (ngSubmit)="onSubmit()">
    
      <div class="panel panel-primary">
    
        <div class="panel-heading">
          <h3 class="panel-title">C3</h3>
        </div>
    
    
        <div class="panel-body">
    
          <div class="form-group">
            <label 
              class="col-sm-2 control-label" 
              for="fullName">
              Full Name
            </label>
    
            <div class="col-sm-8">
              <input 
                id="fullName" 
                type="text" 
                class="form-control" 
                formControlName="firstName">
              <div 
                *ngIf="profileForm.controls['firstName'].touched && profileForm.controls['firstName'].errors.required"
                >
                First Name is required
              </div>
            </div>
          </div>
    
          ...
    
        </div>
    
        ...
    
      </div>
    
    </form>
    

    Also Angular automatically applies classes like ng-invalid and ng-touched on invalid and touched form controls. So you can leverage that to simplify your CSS:

    input.ng-touched.ng-invalid {
      border: 1px solid red;
    }
    

    Here's a Working Sample StackBlitz for your ref.