If I submit a form using button type="submit"
the form validation messages appear and everything is fine. However if I have a button (or link) with (click)="myhandler()"
then the validations do not appear.
How can I either:
- tag the element as requiring validators to run, or
- programatically run and show validation messages.
Note: These are simple validations like required on input fields.
Sample Code:
<form (ngSubmit)="save()">
<input required type='text' [(ngModel)]="name">
<!-- Shows validation messages but still calls save() -->
<button (click)="save()">Click</button>
<!-- Only submits if valid and shows messages -->
<button type="submit">Submit</button>
</form>
<!-- does not even show validation messages, just calls save -->
<button (click)="save()">Click 2</button>
Please note: this approach is for reactive forms.
I used
markAsTouched()
property to run validations on a button click.Suppose the following button is outside the form:
Now, in the
validateForm
method if the form is invalid, you can setmarkAsTouched()
property for each of the form controls and angular will show validation messages.provided you have validation messages setup in your html like
and you have required field validation setup in your form group builder like
Put your
click2
button withinform
tag. It will start working !put conditions in [hidden] directive and change submitted property to true on submit!
You should keep the button disabled until the form is valid. So in your case change your form element opening tag to create a variable for the form:
and disable the button when the form isn't valid
<button (click)="save()" [disabled]="!myForm.form.valid">Click 2</button>
Let me know if that works. As the form itself will validate automatically and constantly in anycase, you dont need to call for it to be done.
Below Code Will Help You .. Tested with Angular 4 Latest version 4.2.4
in Your .ts File
working example http://plnkr.co/edit/aoHHw709VeMlP8Qfgnp6?p=preview