angularangular-reactive-formsangular-formsangular-formbuilderangular20

Angular Reactive Form still includes empty values in form.value even after applying validators


I'm using a Angular 20 with Reactive forms. Even after applying Validators.required to some controls, the form still includes empty string ("") or Null values when I log or submit form.

I have tried following code: html code:

`<form class="px-5" [formGroup]="form" (ngSubmit)="addRecord()">
        <div class="form-group mb-2">
            <label for="fname">FULL NAME</label>
            <input name="fname" type="text" class="form-control" formControlName="fname"
            [ngClass]="{'is-invalid': form.get('fname')?.errors?.['required']}">
        </div>

        <div class="form-group mb-2">
            <label for="email">EMAIL</label>
            <input name="email" type="email" class="form-control" formControlName="email"
            [ngClass]="{'is-invalid': form.get('email')?.errors?.['required']}">
        </div>

        <div class="form-group mb-2">
            <label for="phones">PHONE NUMBERS</label>
            <input name="phones" type="text" class="form-control" formControlName="phones"
            [ngClass]="{'is-invalid': form.get('phones')?.errors?.['required']}">
        </div>

        <div class="form-group mb-3">
            <label for="addr">ADDRESS</label>
            <textarea name="addr" class="form-control" formControlName="addr"></textarea>
        </div>

        <div class="form-group text-center mb-3">
            <button class="btn btn-success me-2">ADD RECORD</button>
            <button type="reset" class="btn btn-info me-2">RESET FORM</button>
           
    </form>
    this.form = this.fb.group({
            id: [0],
            fname: ['', Validators.required],
            email: ['', [Validators.required,Validators.email]],
            phones: ['', Validators.required],
            addr: ['']
     });
     addRecord() {
        if (this.recordData.length == 0) {
            this.counter = 0;
        }
        this.form.value.id = this.counter++;

        this.recordData.push({ ...this.form.value });
        console.log(this.recordData);
     }`

and output was getting: { "id": 0, "fname": "", "email": "shantanup6172@gmail.com", "phones": "08446246172", "addr": "" }

When submitting the form without filling all required fields, the data is still being stored in the array. Instead, it should display validation messages for the empty fields and should not submit until all required data are filled.

github repo : https://github.com/shantanu0708/ng20-demo


Solution

  • When submitting the form, perform a validation so that the user is forced to fill the invalid values.

    submitForm() {
      if(this.form.invalid) {
        this.form.markAllAsTouched();
        alert('Form contains validation issues, kindly provide the mandatory fields.');
        return;
      }
      ... // rest of the save code goes here!
    }
    

    UPDATE:

    So we can add this logic to add row:

     addRecord() {
         if(this.form.invalid) {
           this.form.markAllAsTouched();
           alert('Form contains validation issues, kindly provide the mandatory fields.');
           return;
        }
        if (this.recordData.length == 0) {
            this.counter = 0;
        }
        this.form.value.id = this.counter++;
    
        this.recordData.push({ ...this.form.value });
        console.log(this.recordData);
     }`