简体   繁体   中英

Angular reactive form submits when invalid

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 class="form-signup" [formGroup]="newCustomerForm" (ngSubmit)="validateAllFormFields() && newCustomerForm.valid && registerNewMember()">

<! I am unbale to deactivate this button when form is invalid-->
<button type="submit" class="btn-signup" [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;
  }

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 class="form-horizontal" [formGroup]="form">
 <div class="form-group required">
          <label id="label">Username</label>
          <input class="form-control" id="username" formControlName="UserName">
          <div><div *ngIf="service.Name && service.Name.invalid && (service.Name.dirty || service.Name.touched)"
            class="alert alert-danger">
            <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 class="form-group col-md-8 offset-md-2">
            <button type="submit" class="btn btn-primary btn-block" [disabled]="!form.valid">Submit<button>
          </div>

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 class="form-signup" [formGroup]="newCustomerForm" (ngSubmit)="validateAllFormFields() && newCustomerForm.valid && registerNewMember()">
     <button type="submit" class="btn-signup" [disable]="newCustomerForm.invalid">Sign Up</button>
</form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM