简体   繁体   中英

Angular 2 submits form even with errors

I'm trying to implement a Angular 2 Form with Form Builder. This is my component.html

 <div class="login-container">
  <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.$value)" #f="ngForm" novalidate class="col-md-5">
    <div class="text-center">
      <img src="assets/logo.png" alt="Logo" class="img-fluid">
    </div>
    <input id="username" formControlName="username" type="text" placeholder="Usuario" aria-describedby="Usuario" class="form-control">
    <input id="password" formControlName="password" type="password" placeholder="Contraseña" aria-describedby="Contraseña" class="form-control">
    <button type="submit" class="btn btn-primary btn-block btn-lg">Entrar</button>
  </form>
</div>

And this is my component.ts

...
constructor(
    private router: Router, 
    private authenticationService: AuthService,
    public fb: FormBuilder) { 
      this.loginForm = this.fb.group({
        username: ['', Validators.required],
        password: ['', Validators.required]
      });    
    }
...
login(value:any) {
    this.loading = true;
// Here goes the authentication logic.
      }

But my form always submits even if it has errors, or the inputs are blank. Am I doing anything wrong? Or Does it lack of something?

You're not doing anything wrong, that is the expected behavior the way it is coded. If you don't want the form to submit when there are errors you need to disable your submit button when it is in the invalid state.

<button type="submit" [disabled]="!loginForm.valid" class="btn btn-primary btn-block btn-lg">Entrar</button>

You could send the valid property from the form.

<form [formGroup]="loginForm" #f="ngForm" (ngSubmit)="login(loginForm.$value, f.valid)" novalidate>

And then check it inside the submit function.

login(value:any, valid: boolean) {
    if (!valid) {
      return;
    }

    this.loading = true;
     // Here goes the authentication logic.
 }

If you want to keep the button available but check the form on submit then you can do the following by using ' updateOn: submit ', this is new since Angular5: https://medium.com/codingthesmartway-com-blog/angular-5-forms-update-9587c3735cd3

Or, another option as found here (look for kara's post): https://github.com/angular/angular/issues/14527 :

  <form [formGroup]="heroForm" #formDir="ngForm">
  <div *ngIf="heroForm.hasError('required', 'name') && formDir.submitted">
     Name is required.
  </div>
   <input formControlName="name">
   <input formControlName="power">
   <button [disabled]="heroForm.invalid && formDir.submitted">
      Submit 
   </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