Reputation: 3238
Good morning everyone,
I want to achieve the following behaviour with an ng5 form:
So validation of controls onchange works fine, but what I´m missing is a "form.validate()" method. Also the new "updateOn" feature doesn´t solve this issue, cause then it´s an either-or solution, not a combination of submit- and change validation.
The only solution I found was to develop a validate() method myself which iterates over all controls of a form.
Maybe somebody has an idea for me? :)
Thanks & best, Michael
Upvotes: 1
Views: 2517
Reputation: 1757
Using Reactive Forms will be good. You can achieve everything mentioned here.. https://toddmotto.com/angular-2-forms-reactive
1. Validation:
this.rForm = formBuilder.group({
'email': ['', Validators.compose([Validators.required, Validators.email])] ....
2. Touch events
<div *ngIf="!rForm.controls.email.valid && rForm.controls['email'].touched" class="alert-danger form-alert-bg">
<span *ngIf="rForm.controls.email.errors?.required">
Email is Required*
</span> </div>
3. Disable submit:
<button type="submit" [disabled]="!rForm.valid || response.success"
class="btn btn--circle btn-primary submit-property__button" title="Save">
</button>
Upvotes: 0
Reputation: 234
You could use ReactiveForms.
You can add controls (each html input) to a group, using its validators to check if they are valid. It would take care of all your validation logic underneath and on the submit event all you would have to do to check the form is
form.group.valid
Also, you can check each control individualy to see if its value has been changed, if the user has clicked on it, etc.
There is more info here https://angular.io/guide/reactive-forms
*Note: I can't add comments, that is why I have written this as an answer.
Upvotes: 0
Reputation: 12133
The form is a tree of controls and whenever a single control becomes invalid all of its ancestors become invalid as well.
Whenever the input of a control changes (given you did apply validators) the validity of the control and the form is updated.
Thus, when you hit Submit
you don't really need to run validation again (as it was run on each input change).
All you need for "running validation" is check if the form is valid. You can do this by accessing valid
property of the root FormGroup
:
if(!rootFormGroup.valid)
showErrorPopup();
else
submitForm();
Upvotes: 1