daniel
daniel

Reputation: 35683

Angular validation on form submit

I do validation in angular as following:

<form #f="ngForm" (ngSubmit)="save(f.value, f.valid)" novalidate  >

     <input type="email" name="txtEmail" id="txtEmail" required
          [(ngModel)]="model.txtEmail" #txtEmail="ngModel">
        <div class="msgerror" *ngIf="txtEmail.invalid && (txtEmail.dirty || txtEmail.touched) ">E-Mail invalid</div>

     <button type="submit">Submit</button>

 </form>

How can I trigger the validation on form submit? It only works when pressing keys in the input.

Upvotes: 1

Views: 1819

Answers (2)

Chandru
Chandru

Reputation: 11184

I Think this is way of validating fields after submit. the example is below :

component.html

<form name="editForm" role="form" novalidate (ngSubmit)="save(editForm)" #editForm="ngForm" class="form-horizontal">
    <input type="text" class="form-control" [(ngModel)]="model.txtEmail" name="txtEmail" id="txtEmail" required>
    <div [hidden]="!(editForm.controls.txtEmail?.dirty && editForm.controls.txtEmail?.invalid)">
        <small class="form-text text-danger"
           [hidden]="!editForm.controls.txtEmail?.errors?.required">
           This field is required.
        </small>
    </div>
    <button type="submit" type="submit">Save</button>
</form>

component.ts

import { NgForm } from '@angular/forms';

export class AppComponent {
    private model: any = {};
    private editForm: NgForm;

    save(form: NgForm) {
        this.editForm = form;
        Object.keys(this.editForm.controls).forEach(key => {
            this.editForm.controls[key].markAsDirty();
        })
    }
}

Upvotes: 1

daniel
daniel

Reputation: 35683

i found a solution. I changed:

<div class="msgerror" *ngIf="txtEmail.invalid && (txtEmail.dirty || txtEmail.touched) ">bitte die E-Mail Adresse angeben! </div>

to

<div [hidden]="txtEmail.valid || (txtEmail.pristine && !f.submitted)" class="text-danger">bitte die E-Mail Adresse angeben!  </div>

Upvotes: 0

Related Questions