I have a reactive form in may Angular app. The problem is that the form submits (the page refreshes; I don't see anything in the database; I think it is just the behavior) whenever I try to submit an invalid form.
I want the page to no refresh and display all he invalid fields using my function. Below is a section of my code.
<form [formGroup]="newCustomerForm" (ngSubmit)="validateAllFormFields() && newCustomerForm.valid && registerNewMember()">
<! I am unbale to deactivate this button when form is invalid-->
<button type="submit" [disable]="form.invalid">Sign Up</button>
</form>
//function which makes all fields touched.
public validateAllFormFields(formGroup: FormGroup): boolean {
Object.keys(formGroup.controls).forEach(field => {
const control = formGroup.get(field);
if (control instanceof FormControl) {
control.markAsTouched({ onlySelf: true });
}
else if (control instanceof FormGroup) {
this.validateAllFormFields(control);
}
});
return true;
}
CodePudding user response:
In this example the submit button will only be enabled if the form is valid ([disabled]="!form.valid"), meaning the username must be informed (and also must be a valid username).
form: FormGroup;
onSubmit()
{
this.form=this.fb.group({
UserName:['',[Validators.required,Validators.minLength(4)]]
})
}
<form [formGroup]="form">
<div >
<label id="label">Username</label>
<input id="username" formControlName="UserName">
<div><div *ngIf="service.Name && service.Name.invalid && (service.Name.dirty || service.Name.touched)"
>
<div *ngIf="service.Name && service.Name.errors?.required" >
User Name is required
</div>
<div *ngIf="service.Name && service.Name.errors?.minlength">
Minimum 4 characters required
</div>
</div></div>
</div>
<div >
<button type="submit" [disabled]="!form.valid">Submit<button>
</div>
CodePudding user response:
What is your form variable name? Is it newCustomerForm
or just form
?
Also, you have written [disable]="form.invalid" instead of [disabled]="newCustomerForm.invalid". (if your form name is newCustomerForm)
<form [formGroup]="newCustomerForm" (ngSubmit)="validateAllFormFields() && newCustomerForm.valid && registerNewMember()">
<button type="submit" [disable]="newCustomerForm.invalid">Sign Up</button>
</form>