2

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": "[email protected]", "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

1
  • Even if this form is prevented from submitting to the backend, that doesn't prevent someone else from doing so without using your form. Make sure the backend is hardened against invalid values. Commented Oct 10 at 6:08

2 Answers 2

2

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);
 }`
Sign up to request clarification or add additional context in comments.

5 Comments

The form still shows the validation alert, but this approach is definitely better than the earlier version where errors occurred.
[deleted]
[deleted]
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.
[deleted]
[deleted]
I have specified in addRecord function, this.recordData
[deleted]
[deleted]
But it still gives popup alert message. Is there any other way (if) to handle this?
[deleted]
[deleted]
Instead use of alert we can use if directive in html code like following to avoid popup message @if(form.get('fname')?.errors?.['required'] && form.get('fname')?.touched) { <div class="text-danger"> Full Name is required </div> }
2

I think the following is perfect solution which combines

this.form.markAllAsTouched();

and

@if(form.get('fname')?.errors?.['required'] && form.get('fname')?.touched) 
{ 
<div class="text-danger"> 
Full Name is required 
</div> 
}

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">

            @if(form.get('fname')?.errors?.['required'] && form.get('fname')?.touched) {
                <div class="text-danger">
                    Full Name is required
                </div>
            }
        </div>

        <div class="form-group mb-2">
            <label for="email">EMAIL</label>
            <input name="email" type="email" class="form-control" formControlName="email">

            @if(form.get('email')?.errors?.['required'] && form.get('email')?.touched) {
            <div class="text-danger">
                Email is required
            </div>
            }
            @if(form.get('email')?.errors?.['email'] && form.get('email')?.touched) {
            <div class="text-danger">
                Invalid email format
            </div>
            }
        </div>
    <div class="form-group mb-2">
            <label for="phones">PHONE NUMBERS</label>
            <input name="phones" type="text" class="form-control" formControlName="phones">

            @if(form.get('phones')?.errors?.['required'] && form.get('phones')?.touched) {
            <div class="text-danger">
                Phones is required
            </div>
            }
        </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 type="submit" class="btn btn-success me-2">ADD RECORD</button>
            <button type="reset" class="btn btn-info me-2">RESET FORM</button>
    </form>

Typescript code :

this.form = this.fb.group({
            id: [0],
            fname: ['', Validators.required],
            email: ['', [Validators.required,Validators.email]],
            phones: ['', Validators.required],
            addr: ['']
        });

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.