0

I am trying to create a simple user registration project in angular.I'm trying to validate that no field is left empty in the form.However I'm unable to do so.

Here is my ts code:

export class AdduserComponent implements OnInit {


  constructor(private formBuilder:FormBuilder,private userService:UsersService,private router:Router) { }
  addForm: FormGroup;
  selected = 'option2';

  ngOnInit() {

    this.addForm = this.formBuilder.group({
      id: [],
      userName: ['', Validators.required],
      password: ['', Validators.required],
      userRole:['',Validators.required],
    });
  }
  onSubmit() {
    this.userService.createUser(this.addForm.value)
      .subscribe( data => {
        this.router.navigate(['adduser']);
      });
    console.log(this.addForm.value);
  }
  changeClient(value) {
    console.log(value);
}
}

Here is my template:

<form [formGroup]="addForm" class="login-form" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <mat-form-field class="example-full-width">

      <input matInput type="text" formControlName="userName" placeholder="userName" name="userName" class="form-control" id="userName">
        </mat-form-field>
    </div>

    <div class="form-group">
        <mat-form-field class="example-full-width">

      <input matInput type="password" formControlName="password" placeholder="Password" name="password" class="form-control" id="password">
    </mat-form-field>
    </div>

    <mat-form-field>
        <mat-select panelClass="example-panel-blue.mat-select-panel" placeholder="Roles" formControlName="userRole" id="userRole" (selectionChange)="changeClient($event.value)" [(value)]="selected">
          <mat-option value="Admin">Admin</mat-option>


        </mat-select>
      </mat-form-field>
      <div class="container" style="margin: 12px" fxLayout="row" fxLayoutAlign="center center">


    <button mat-raised-button color="primary">Create</button>
      </div>
  </form>

I've added validators but still I'm able to create user with null values.Please help.Thanks in advance

major7
  • 1
  • 1
  • 4

3 Answers3

3

An invalid form won't stop you from triggering (ngSubmit).

Do a form validity check in onSubmit() and then create the users.

onSubmit() {
    if (this.addForm.valid) {
          this.userService.createUser(this.addForm.value)
          .subscribe( data => {
                   this.router.navigate(['adduser']);
          });
    }
}
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
  • 1
    If you want to get error instantly means not waiting for submitting or say click on submit you can do as below: https://stackblitz.com/angular/egbexnbeopl?file=app%2Finput-error-state-matcher-example.ts – Niraj Apr 10 '19 at 07:22
  • @NirajOza Yeah, haven't worked on material, but this `ErrorStateMatcher` is nice.I had been showing error messages by checking the values of form's touched property and the controls' errors and some other flags maybe. Thanks! – Ashish Ranjan Apr 10 '19 at 07:30
0

You have to check yourself if the form is valid, it wont block a submit for you - https://angular.io/api/forms/NgForm:

  onSubmit() {
    if(this.addForm.valid) {
      this.userService.createUser(this.addForm.value)
        .subscribe( data => {
          this.router.navigate(['adduser']);
        });
      console.log(this.addForm.value);  
     }
  }
J. Knabenschuh
  • 747
  • 4
  • 15
0

You can validate your data as soon as any value changes in the form, no need to wait for the submit to happen.

Here is an example to validate strings that are not empty spaces, you can change it to your needs.

game-start.component.ts

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

@Component({
  selector: 'app-game-start',
  templateUrl: './game-start.component.html',
  styleUrls: ['./game-start.component.css']
})
  
export class GameStartComponent implements OnInit {
  playerInfo = new FormGroup({
    playerOneName: new FormControl('', [Validators.required, this.WhitespacesInvalid]),
    playerTwoName: new FormControl('', [Validators.required, this.WhitespacesInvalid]),
  });

  constructor() {  }

  public WhitespacesInvalid(control: FormControl) {
    const isWhitespace = (control.value || '').trim().length === 0;
    const isValid = !isWhitespace;
    return isValid ? null : { 'whitespaceInvalid': true };
  }

  ngOnInit(): void {
  }

  onSubmit() {
    // TODO: Use EventEmitter with form value
    console.warn(this.playerInfo.value);
    console.warn(this.playerInfo);
  }
}

Above the WhitespacesInvalid custom validator is declared and used when creating the FormControls in the constructor

In the HTML the hasError function is used to check for 'whitespaceInvalid' when the values are changed in the form, there no need to wait for the submit to happen, also the submit button is only enabled when all the validators are OK.

game-start.component.html

<h2>Welcome to Game of Drones</h2>
<h2>Enter Player's Names</h2>

<form [formGroup]="playerInfo" (ngSubmit)="onSubmit()">
  <label>
    Player 1:
    <input type="text" formControlName="playerOneName">
  </label>

  <label>
    Player 2:
    <input type="text" formControlName="playerTwoName">
  </label>

  <button type="submit" [disabled]="!playerInfo.valid">START</button>

  <div *ngIf="playerInfo.controls['playerOneName'].hasError('whitespaceInvalid')" class="alert alert-danger">
    Player 1 name can not be empty.
  </div>

  <div *ngIf="playerInfo.controls['playerTwoName'].hasError('whitespaceInvalid')" class="alert alert-danger">
    Player 2 name can not be empty.
  </div>

</form>

The custom validator was taken from this question.

How to validate white spaces/empty spaces? [Angular 2]

Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99