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.
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 }
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With