Lijin Durairaj
Lijin Durairaj

Reputation: 3501

How to validate a form on button submit

I have a form, which is getting validated once the control gets the class change from ng-untouched ng-pristine ng-invalid to ng-pristine ng-invalid ng-touched but if i have a form with more controls then i want the user to know which field he/she has missed out on the button submit. how can i do that using angularJS2. I have used ReactiveFormsModule to validate the controls

The following is my code: component

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

@Component({
    selector: 'page',
    templateUrl:'../app/template.html'
})
export class AppComponent {
    registrationForm: FormGroup;
    constructor(private fb: FormBuilder) {
        this.registrationForm = fb.group({
            username: ['', [Validators.required, Validators.minLength(4)]],
            emailId: ['', [Validators.required, this.emailValidator]],
            phonenumber: ['', [Validators.required, this.phoneValidation]]           
        })
    }

    emailValidator(control: FormControl): { [key: string]: any } {
        var emailRegexp = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
        if (control.value && !emailRegexp.test(control.value)) {
            return { invalidEmail: true };
        }
    }
    phoneValidation(control: FormControl) {
        if (control['touched'] && control['_value'] != '') {
            if (!/^[1-9][0-9]{10}$/.test(control['_value'])) {
                return { 'invalidPhone': true }
            }
        }
    }
}

The following is my code: module

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';

import { AppComponent } from '../app/component';
@NgModule({
    imports: [BrowserModule, ReactiveFormsModule],
    declarations: [AppComponent],
    bootstrap: [AppComponent]
})
export class AppModule { }

The following is my code: template

<form [formGroup]="registrationForm" (ngSubmit)="registrationForm.valid && submitRegistration(registrationForm.value)">
    <input type="text" formControlName="username"  placeholder="username" />
    <div class='form-text error' *ngIf="registrationForm.controls.username.touched">
        <div *ngIf="registrationForm.controls.username.hasError('required')">Username is required.</div>

    </div>
    <br />
    <input type="text" formControlName="emailId"  placeholder="emailId" />
    <div class='form-text error' *ngIf="registrationForm.controls.emailId.touched">
        <div *ngIf="registrationForm.controls.emailId.hasError('required')">email id is required.</div>
        <div *ngIf="registrationForm.controls.emailId.hasError('invalidEmail')">
            Email is not in correct format.
        </div>
    </div>
    <br />
    <input type="text" formControlName="phonenumber"  placeholder="phonenumber" />
    <div class='form-text error' *ngIf="registrationForm.controls.phonenumber.touched">
        <div *ngIf="registrationForm.controls.phonenumber.hasError('required')">phone number is required.</div>      
        <div *ngIf="registrationForm.controls.phonenumber.hasError('invalidPhone')">Invalid phone number.</div>   
    </div>
    <br />
    <input type="submit" value="Submit" />
</form>

I thought of updating all the invalid controls class to ng-untouched ng-pristine ng-invalid but not sure if this is the right approach

Upvotes: 2

Views: 1027

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657308

Angular forms don't provide ways to specify when to do validation.

Just set a flag to true when the form is submitted and show validation warnings only when the flag is true using *ngIf="flag" or similar.

<form [formGroup]="registrationForm" (ngSubmit)="submitRegistration(registrationForm.value)">

<div *ngIf="showValidation> validation errors here </div>

showValidation:boolean = false;

submitRegistration() {
  if(this.registrationForm.status == 'VALID') {
    this.processForm();
  } else {
    this.showValidation = true;
  }
}

Upvotes: 2

Related Questions