Snake
Snake

Reputation: 323

Angular 2 Trigger Form Validation on Submit

I created a form with angular 2 and added some custome validators. Now i want to trigger the form validation if the user clicks on the submit button. In the examples i have found so far the submit button is disabled as long as the form is invalid but i want to have the submit button always enable and when the user clicks on submit the form should be validated. Does anybody know how i can make this work and which typescript method i should use? I have found the updateValueAndValidity method but it doesn´t seem to work with this method.

Upvotes: 14

Views: 24270

Answers (5)

Dheeraj Kumar
Dheeraj Kumar

Reputation: 146

component html file: You have to add form group model into form tag and ngsubmit method to call the submit function while submitting the form. Please add the formControlName in each input field and the name should be same which you have declared in component ts file. mat-error is to show the validation error. we are passing one return type function in *ngIf which will validate the control error and return back true or false. if it returns true then we are showing mat-error.

<form [formGroup]="Addform" (ngSubmit)="submit(Addform)">
   <h1 mat-dialog-title>Add Field</h1>
   <mat-dialog-content>
      <mat-form-field>
         <input matInput formControlName="make" placeholder="Make...">
         <mat-error *ngIf="hasError('make', 'required')">Make is required</mat-error>
      </mat-form-field>
   </mat-dialog-content>
</form>

component ts file first we have to declare the AddForm group with type of FormGroup. and using the FormBuilder we have to set the rules to this particular form group.

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

@Component({
  selector: 'app-comp',
  templateUrl: './app-comp.html'
})

export class CustomAddForm implements OnInit {
   Addform: FormGroup;
   submitted = false; // by default set submitted to false
   constructor(
     private formBuilder: FormBuilder
   ) {}

   ngOnInit() {
     // initialization time assign the form control rules to form builder.
     this.Addform = this.formBuilder.group({
      make: ['', Validators.required]
     })
   }

   // getter function to provide the control validation info to html 
   public hasError = (controlName: string, errorName: string) =>{
      return this.Addform.controls[controlName].hasError(errorName);
    }

   // submit function
   submit(Addform) {
      if (this.Addform.invalid) { 
      // if condition to check the form group validation.
      // show validation alert here.
         return;
     }

      this.submitted = true;
      // add you success code here.

   }

}

Upvotes: 0

Nagender Pratap Chauhan
Nagender Pratap Chauhan

Reputation: 2204

You can do both of the validation ( on submit button show all error with the error message and individually error message ) by the help of Angular Material (MatFormFieldModule). After a long R&D, my problem resolved but firstly you will be taken sound knowledge of angular material.

Example code:-

<form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value,loginForm)"> 
 <mat-form-field>
    <input matInput placeholder="Enter your email" formControlName="email">
      <mat-error *ngIf="loginForm.controls['email'].hasError('required')">Required</mat-error>
      <mat-error *ngIf="loginForm.controls['email'].hasError('email')">Invalid Mail</mat-error>
 </mat-form-field>
</form>

login.ts file code :

private createLoginForm() {
  this.loginForm = this.fb.group({
    email: new FormControl('', [Validators.required, Validators.email]),
  })
}  

You can attach more validator according to your requirement.

Upvotes: 0

Yuriy Yakovenko
Yuriy Yakovenko

Reputation: 75

(Reactive Form)

Had problem with it my solution is:

-- Template

<button type="button" (click)="f.ngSubmit.emit(f)">Submit From Outside 
form</button>

<form novalidate #f="ngForm" (ngSubmit)="save($event)" 
[formGroup]="MyformGroup">
...
</form>

-- Class

@ViewChild('f') f: FormGroupDirective;

submit(formDirective: FormGroupDirective) {
  console.log('valid', formDirective.valid);
  console.log('value', formDirective.value);
}

This is solution that i use to submit form with some button that is not in form.

Thanks

Upvotes: 0

DaniS
DaniS

Reputation: 3479

The validation should be executed everytime you change the model. But perhaps you can't see the error message because the FormControl is untouched? Here is my solution which works fine.

I did it with the following easy steps:

  1. Implement a FormComponent (selector "form") which injects the formGroupDirective (subscribe to the submit event and set submitted as true)

    @Component({
        selector: 'form',
        templateUrl: 'form.component.html',
        styleUrls: ['form.component.scss']
    })
    export class FormComponent implements OnInit {
        @Output() submit = new EventEmitter();

        constructor(@Optional() private formGroupDirective: FormGroupDirective) {
        }

        ngOnInit() {
            if (this.formGroupDirective) {
                this.formGroupDirective.ngSubmit.subscribe(() => {
                    this.formGroupDirective.form['submitted'] = true;
                });
            }
        }

    }

The important lines are in ngOnInit

  1. Check for form submitted to show the error

    *ngIf="control?.hasError('required') && (control?.touched || form?.submitted)"

Hope that helps

Upvotes: 1

dev_in_progress
dev_in_progress

Reputation: 2494

If you are using Template Driven Form you can use this syntax:

<form #f="ngForm" (submit)="add(f.valid)" novalidate>
    <button type="submit">Save</button>
</form>

.ts

add(isValid: boolean){
   if(isValid){
       //do something
   }
}

you can also add some errors on submit like this:

<form #f="ngForm" (submit)="add(f.valid)" novalidate>
    <label>Name</label>
    <div>
        <input [(ngModel)]="name" name="name" #name="ngModel" required>
    </div>
    <div[hidden]="name.valid || (name.pristine && !f.submitted)">
        <small class="text-danger">Please input name</small>
    </div>
    <button type="submit">Save</button>
</form>

Upvotes: 15

Related Questions