Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 910
Snake Avatar asked Oct 24 '16 09:10

Snake


People also ask

What is ValidatorFn in Angular?

ValidatorFnlinkA function that receives a control and synchronously returns a map of validation errors if present, otherwise null. interface ValidatorFn { (control: AbstractControl<any, any>): ValidationErrors | null }

What is AbstractControl in Angular?

It provides some of the shared behavior that all controls and groups of controls have, like running validators, calculating status, and resetting state. It also defines the properties that are shared between all sub-classes, like value , valid , and dirty . It shouldn't be instantiated directly.


1 Answers

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>
like image 106
dev_in_progress Avatar answered Oct 13 '22 03:10

dev_in_progress